Skip to content

Fix format() printing 1024 in the auto-selected unit - #74

Closed
afonsojanu wants to merge 1 commit into
visionmedia:masterfrom
afonsojanu:fix/format-unit-rollover-boundary
Closed

afonsojanu wants to merge 1 commit into
visionmedia:masterfrom
afonsojanu:fix/format-unit-rollover-boundary

Conversation

@afonsojanu

Copy link
Copy Markdown

format() auto-picks a unit for a byte count by comparing the raw value against each threshold (>= 1024 for KB, >= 1024**2 for MB, and so on), then divides and rounds to decimalPlaces. That rounding step can push a value that was just under a threshold back up to (or past) 1024 in the unit that already got picked:

require('bytes').format(1048575.995, { decimalPlaces: 2 })
// => '1024.00KB'   (should be '1MB')

require('bytes').format(1073741823.9999, { decimalPlaces: 2 })
// => '1024.00MB'   (should be '1GB')

1024.00KB and 1MB are the same amount, but printing it in the unit that was supposed to be "too small for this" defeats the whole point of the auto-selection, and reads as if it just failed to notice it crossed the boundary.

The fix re-checks after rounding: if the formatted magnitude still reads >= 1024 and there's a bigger unit available, it moves up and reformats against that unit instead (looping in case one bump isn't enough, though in practice one is). This only applies when the unit was auto-selected — passing an explicit unit option is a deliberate choice and is left alone, so bytes.format(1048575.995, { decimalPlaces: 2, unit: 'KB' }) still prints 1024KB.

Added a test ("Should never round the displayed value up to the next unit's threshold") covering the KB/MB/GB/TB/PB boundaries, negative values, and the explicit-unit case. Confirmed it fails on the unpatched index.js and passes with the fix; npm test (mocha) and npm run lint (eslint) both still pass with no new warnings.

When decimalPlaces rounding pushes a value that was just under a unit
boundary up to 1024, format() kept the smaller unit instead of rolling
over, e.g. bytes(1048575.995, { decimalPlaces: 2 }) printed '1024.00KB'
instead of '1MB'. Only the auto-selected unit is corrected; an
explicitly requested unit is left as the caller asked for it.
@afonsojanu

Copy link
Copy Markdown
Author

Closing this one too, same reason: starting fresh and clearing out everything I had open.

@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.

1 participant