avoidwork / filesize.js

JavaScript library to generate a human readable String describing the file size
https://filesizejs.com
BSD 3-Clause "New" or "Revised" License
1.61k stars 97 forks source link

pad fails without separator when decimal places are zero #184

Closed Hamper closed 1 month ago

Hamper commented 1 month ago

The 'pad' method doesn't work when the separator is not set and all decimal places are zero.

> filesize(1100)
'1.1 kB'
> filesize(1100, {round: 2, pad: true})
'1.10 kB'
> filesize(1100, {round: 2, pad: true, separator: '.'})
'1.10 kB'

> filesize(1001)
'1 kB'
> filesize(1001, {round: 2, pad: true})
'1 kB' // must be '1.00 kB'
> filesize(1001, {round: 2, pad: true, separator: '.'})
'1.00 kB'
avoidwork commented 1 month ago

I think you want to use precision; the default value of separator is an empty string so that it doesn't count as an incomplete float when the string concatenation happens.

The precision value always forces the number of digits (significant numbers); it's just Number.toPrecision() on the calculated number.

filesize(1001, {precision: 3}); // 1.00 kB
filesize(1024, {precision: 3, base: 2}); // 1.00 KiB

As described, the pad option enhances a potential decimal value; it will not turn an integer into a float.

avoidwork commented 1 month ago

A precision of 3 will give you xxx, xx.x, x.xx, & .xxx as potential formatted outputs. I think this is what most users would be after if you want to have decimal numbers.

However, if you don't want to use precision you have to set separator to . for the desired behavior, because in that scenario you're setting the character to append to the integer while creating the string. This approach runs into localization issues quickly.

Hamper commented 1 month ago

I need to always have 2 decimal places, for example

  x.xx
 xx.xx
xxx.xx

And this work when separator is not empty, but don't work with default value

precision also has other potential problems like this:

> filesize(110, {precision: 2})
'1.1e+2 B'
avoidwork commented 1 month ago

This is fixed in 10.1.5 👍🏻