avoidwork/filesize.js

pad fails without separator when decimal places are zero

Closed this issue · 4 comments

Hamper commented

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'

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.

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

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'

This is fixed in 10.1.5 👍🏻