Skip to content

Commit

Permalink
Change how the 0 flag works in format! for floats
Browse files Browse the repository at this point in the history
Now it always implies right-alignment, so that padding zeroes are placed after the sign (if any) and before the digits. In other words, it always takes precedence over explicitly specified `[[fill]align]`.

               :06      :<06     :>06     :^06
    before   |-001.2| |-1.200| |-001.2| |-01.20|
    after    |-001.2| |-001.2| |-001.2| |-001.2|
  • Loading branch information
Sawyer47 authored and alexcrichton committed Mar 15, 2017
1 parent ff63866 commit 8065486
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/libcore/fmt/mod.rs
Expand Up @@ -1154,8 +1154,9 @@ impl<'a> Formatter<'a> {
// for the sign-aware zero padding, we render the sign first and
// behave as if we had no sign from the beginning.
let mut formatted = formatted.clone();
let mut align = self.align;
let old_fill = self.fill;
let old_align = self.align;
let mut align = old_align;
if self.sign_aware_zero_pad() {
// a sign always goes first
let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
Expand All @@ -1166,6 +1167,7 @@ impl<'a> Formatter<'a> {
width = if width < sign.len() { 0 } else { width - sign.len() };
align = rt::v1::Alignment::Right;
self.fill = '0';
self.align = rt::v1::Alignment::Right;
}

// remaining parts go through the ordinary padding process.
Expand All @@ -1178,6 +1180,7 @@ impl<'a> Formatter<'a> {
})
};
self.fill = old_fill;
self.align = old_align;
ret
} else {
// this is the common case and we take a shortcut
Expand Down
12 changes: 12 additions & 0 deletions src/test/run-pass/ifmt.rs
Expand Up @@ -176,6 +176,18 @@ pub fn main() {
t!(format!("{:<#05x}", 1), "0x001");
t!(format!("{:>#05x}", 1), "0x001");
t!(format!("{:^#05x}", 1), "0x001");
t!(format!("{:05}", 1.2), "001.2");
t!(format!("{:<05}", 1.2), "001.2");
t!(format!("{:>05}", 1.2), "001.2");
t!(format!("{:^05}", 1.2), "001.2");
t!(format!("{:05}", -1.2), "-01.2");
t!(format!("{:<05}", -1.2), "-01.2");
t!(format!("{:>05}", -1.2), "-01.2");
t!(format!("{:^05}", -1.2), "-01.2");
t!(format!("{:+05}", 1.2), "+01.2");
t!(format!("{:<+05}", 1.2), "+01.2");
t!(format!("{:>+05}", 1.2), "+01.2");
t!(format!("{:^+05}", 1.2), "+01.2");

// Ergonomic format_args!
t!(format!("{0:x} {0:X}", 15), "f F");
Expand Down

0 comments on commit 8065486

Please sign in to comment.