Skip to content

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

Merged
robjtede merged 1 commit into
bytesize-rs:masterfrom
sueun-dev:fix-display-width-precision
Jul 31, 2026
Merged

fix: honor precision when a width is set in ByteSize Display#178
robjtede merged 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
Contributor

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.
@robjtede
robjtede force-pushed the fix-display-width-precision branch from 605fd38 to df1d9e1 Compare July 31, 2026 12:34
@robjtede
robjtede enabled auto-merge (squash) July 31, 2026 13:13

@robjtede robjtede left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

very subtle, nice one, thanks 👍🏻

@robjtede
robjtede merged commit c4172ca into bytesize-rs:master Jul 31, 2026
11 checks passed
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.

2 participants