Skip to content

fix: prevent 1000 unit prefix output by rolling over on boundary rounding - #169

Closed
AdamMagued wants to merge 1 commit into
dustin:masterfrom
AdamMagued:fix-bytes-unit-boundary-rounding
Closed

AdamMagued wants to merge 1 commit into
dustin:masterfrom
AdamMagued:fix-bytes-unit-boundary-rounding

Conversation

@AdamMagued

Copy link
Copy Markdown

Summary

When formatting byte values near unit boundaries (such as 999_950 bytes, MByte - Byte, or MiByte - IByte), rounding to the required display precision can produce values equal to the base magnitude (e.g. 1000 kB or 1024 KiB) instead of rolling over to the next unit (1.0 MB or 1.0 MiB).

Root Cause

In humanateBytes:

  1. The magnitude index e is determined by math.Floor(logn(float64(s), base)) on the unrounded value.
  2. The normalized value val = float64(s) / math.Pow(base, e) is computed and rounded according to minDigits.
  3. If val rounds up to base (e.g. 999.95 rounds to 1000.0 with base 1000), no check existed to advance the magnitude index. Consequently, formatting emitted strings such as "1000 kB" or "1024 KiB".

Solution

  • After rounding, check if val >= base and an upper unit exists (int(e) < len(sizes)-1).
  • If so, advance e++, rescale val /= base, and recompute display precision digits based on the new integer digit count.
  • Update test cases expecting unit rollover at boundary conditions and add regression tests for boundary inputs.

Fixes #127

…ding

When byte values close to a unit boundary (such as 999,950 bytes or
MByte - Byte) are formatted, rounding at the display precision can cause
the formatted value to reach the unit threshold (e.g. 1000 kB or 1024 KiB)
instead of rolling over into the next unit (e.g. 1.0 MB or 1.0 MiB).

This change checks whether the rounded value reaches or exceeds the base
threshold before emitting the formatted string. If so, and if higher unit
sizes are available, the magnitude exponent is incremented, the value is
scaled by the base, and formatting digits are recalculated.

Fixes dustin#127
@AdamMagued

Copy link
Copy Markdown
Author

Closing in favor of earlier community PR #160 to avoid duplicate review effort.

@AdamMagued AdamMagued closed this Oct 2, 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.

Don't output 1000 kB for 1.0 MB

1 participant