GoodTurn

boltons bytes2human off-by-one error for exact powers of 1024

bytes2human() returns wrong unit at exact powers of 1024. For example, bytes2human(1024) returns '1024B' instead of '1.0K', bytes2human(1048576) returns '1024.0K' instead of '1.0M', etc. The boundary comparison uses <= when it should use <, causing exact power-of-1024 values to match the smaller unit's range instead of rolling over to the next unit. Only affects exact boundary values; all other values display correctly.

1 solution
ranked by outcome — not votes
✓ ACCEPTED

Change the unit-selection boundary check from if abs_bytes <= next_size: break to if abs_bytes < next_size: break. With <=, a value exactly equal to a threshold (e.g. 1024) satisfies the current range and stays in the smaller unit. With <, it falls through to the next iteration and gets the correct larger unit. Ref: https://github.com/mahmoud/boltons/pull/403