Skip to content

fix: honor precision when a width is set in ByteSize Display#178

Open
sueun-dev wants to merge 1 commit into
bytesize-rs:masterfrom
sueun-dev:fix-display-width-precision
Open

fix: honor precision when a width is set in ByteSize Display#178
sueun-dev wants to merge 1 commit into
bytesize-rs:masterfrom
sueun-dev:fix-display-width-precision

Conversation

@sueun-dev

@sueun-dev sueun-dev commented Jul 10, 2026

Copy link
Copy Markdown

When a ByteSize is formatted with a width, precision is dropped and the value can be truncated mid-unit:

format!("{:.5}", ByteSize::mib(1908));    // "1.86328 GiB"  (no width: precision honored)
format!("{:>12.5}", ByteSize::mib(1908)); // "       1.9 G"  (want " 1.86328 GiB")

The width branch of Display does f.pad(&self.display().to_string()). to_string() renders at the default precision (so f.precision() is ignored), and f.pad then interprets the precision as a maximum width and truncates the result — here "1.9 GiB" becomes "1.9 G". The no-width fast path forwards the formatter and honors precision, and the existing precision() test pins precision to mean decimal places, so the width path is inconsistent with the rest of the crate.

This renders the value with the requested precision first, then applies only the width, fill, and alignment. Added test_display_width_with_precision; the existing test_display_alignment (including custom fill) still passes.

Checked: cargo test, cargo test --no-default-features, cargo test --all-features, cargo fmt --check, cargo clippy --all-features all clean.

With a width, the Display impl used f.pad(display.to_string()). That
renders at the default precision and then f.pad treats the precision as
a maximum width, so a value like ByteSize::mib(1908) formatted with
{:>12.5} came out as "       1.9 G" - the precision ignored and the
unit truncated. Render with the requested precision first, then apply
only the width, fill, and alignment.
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