Skip to content

Fix trailing zero stripping when a leading fraction digit is zero - #73

Closed
afonsojanu wants to merge 1 commit into
visionmedia:masterfrom
afonsojanu:fix-decimal-places-trailing-zeros
Closed

afonsojanu wants to merge 1 commit into
visionmedia:masterfrom
afonsojanu:fix-decimal-places-trailing-zeros

Conversation

@afonsojanu

Copy link
Copy Markdown

Closes #69.

format() is supposed to trim trailing zeros from the fixed-point output unless fixedDecimals is set, but the regex doing that (/(?:\.0*|(\.[^0]+)0+)$/) only covers two shapes: an all-zero fraction, or a fraction whose very first digit is non-zero. It misses anything in between, such as 1075 bytes with decimalPlaces: 3, whose toFixed(3) output is "1.050". Neither branch of the old regex matches that string (the first requires every fraction digit to be zero, the second requires the digit right after the dot to be non-zero), so the extra zero survives and you get "1.050KB" instead of "1.05KB".

require('bytes')(1536, { decimalPlaces: 3 }) // '1.5KB'  (fine, digit after dot is 5)
require('bytes')(1075, { decimalPlaces: 3 }) // '1.050KB' (bug, digit after dot is 0)

Swapped it for a plain "trim trailing zeros after the dot" pattern plus a second pass to drop a now-bare trailing dot (handles the all-zero case like 1.000 -> 1). Ran the existing suite plus a small fuzz check across random values and decimalPlaces 0-5 and didn't find any case left with a stray trailing zero or dangling dot.

Added a test in test/byte-format.js covering the reported input along with the pre-existing all-zero-fraction case to make sure that one still collapses correctly.

format() drops trailing zeros from the fixed-point string unless
fixedDecimals is set, but the old regex only handled that when the
first digit after the decimal point was non-zero. A value like
1075 bytes formatted with decimalPlaces: 3 produces toFixed output
"1.050", and neither alternative in the old pattern matched it, so
the trailing zero was left in place ("1.050KB" instead of "1.05KB").

Replaced it with a simpler pattern that just trims trailing zeros
after the decimal point, followed by a second pass that drops a
now-bare trailing dot (covers the all-zero-fraction case, e.g. "1.000"
-> "1"). Added a test covering the reported case plus the existing
all-zero case.
@afonsojanu

Copy link
Copy Markdown
Author

Closing this for now as part of a clean slate — stepping back from everything I had open across these repos.

@afonsojanu afonsojanu closed this Oct 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

decimalPlaces is incosistent

1 participant