1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 03:27:44 +00:00

uucore: format: Pad non-finite numbers with spaces, not zeros

`printf "%05.2f" inf` should print `  inf`, not `00inf`.

Add a test to cover that case, too.
This commit is contained in:
Nicolas Boichat 2025-03-16 20:10:18 +01:00 committed by Sylvestre Ledru
parent ec450d602a
commit 25c492ee19
2 changed files with 27 additions and 2 deletions

View file

@ -253,6 +253,8 @@ impl Formatter<&ExtendedBigDecimal> for Float {
ExtendedBigDecimal::MinusNan => (ExtendedBigDecimal::Nan, true),
};
let mut alignment = self.alignment;
let s = match abs {
ExtendedBigDecimal::BigDecimal(bd) => match self.variant {
FloatVariant::Decimal => {
@ -268,11 +270,17 @@ impl Formatter<&ExtendedBigDecimal> for Float {
format_float_hexadecimal(&bd, self.precision, self.case, self.force_decimal)
}
},
_ => format_float_non_finite(&abs, self.case),
_ => {
// Pad non-finite numbers with spaces, not zeros.
if alignment == NumberAlignment::RightZero {
alignment = NumberAlignment::RightSpace;
};
format_float_non_finite(&abs, self.case)
}
};
let sign_indicator = get_sign_indicator(self.positive_sign, negative);
write_output(writer, sign_indicator, s, self.width, self.alignment)
write_output(writer, sign_indicator, s, self.width, alignment)
}
fn try_from_spec(s: Spec) -> Result<Self, FormatError>

View file

@ -990,6 +990,23 @@ fn float_flag_position_space_padding() {
.stdout_only(" +1.0");
}
#[test]
fn float_non_finite_space_padding() {
new_ucmd!()
.args(&["% 5.2f|% 5.2f|% 5.2f|% 5.2f", "inf", "-inf", "nan", "-nan"])
.succeeds()
.stdout_only(" inf| -inf| nan| -nan");
}
#[test]
fn float_non_finite_zero_padding() {
// Zero-padding pads non-finite numbers with spaces.
new_ucmd!()
.args(&["%05.2f|%05.2f|%05.2f|%05.2f", "inf", "-inf", "nan", "-nan"])
.succeeds()
.stdout_only(" inf| -inf| nan| -nan");
}
#[test]
fn float_abs_value_less_than_one() {
new_ucmd!()