AK: Add support for keeping trailing zeros in fixed precision floats

This uses the same syntax as zero padding integers:
String::formatted("{:0.5}", 1.234) => "1.23400"
This commit is contained in:
Idan Horowitz 2021-06-19 17:00:31 +03:00 committed by Linus Groh
parent 4d5ffd364a
commit 5e53a690ac
Notes: sideshowbarker 2024-07-18 12:00:56 +09:00
3 changed files with 15 additions and 3 deletions

View file

@ -334,6 +334,7 @@ void FormatBuilder::put_f64(
double value,
u8 base,
bool upper_case,
bool zero_pad,
Align align,
size_t min_width,
size_t precision,
@ -367,10 +368,14 @@ void FormatBuilder::put_f64(
epsilon *= 10.0;
}
if (visible_precision > 0) {
if (zero_pad || visible_precision > 0)
string_builder.append('.');
if (visible_precision > 0)
format_builder.put_u64(static_cast<u64>(value), base, false, upper_case, true, Align::Right, visible_precision);
}
if (zero_pad && (precision - visible_precision) > 0)
format_builder.put_u64(0, base, false, false, true, Align::Right, precision - visible_precision);
}
put_string(string_builder.string_view(), align, min_width, NumericLimits<size_t>::max(), fill);
@ -623,7 +628,7 @@ void Formatter<double>::format(FormatBuilder& builder, double value)
m_width = m_width.value_or(0);
m_precision = m_precision.value_or(6);
builder.put_f64(value, base, upper_case, m_align, m_width.value(), m_precision.value(), m_fill, m_sign_mode);
builder.put_f64(value, base, upper_case, m_zero_pad, m_align, m_width.value(), m_precision.value(), m_fill, m_sign_mode);
}
void Formatter<float>::format(FormatBuilder& builder, float value)
{

View file

@ -189,6 +189,7 @@ public:
double value,
u8 base = 10,
bool upper_case = false,
bool zero_pad = false,
Align align = Align::Right,
size_t min_width = 0,
size_t precision = 6,

View file

@ -252,6 +252,12 @@ TEST_CASE(yay_this_implementation_sucks)
EXPECT_EQ(String::formatted("{:.0}", .99999999999), "0");
}
TEST_CASE(precision_with_trailing_zeros)
{
EXPECT_EQ(String::formatted("{:0.3}", 1.12), "1.120");
EXPECT_EQ(String::formatted("{:0.1}", 1.12), "1.1");
}
TEST_CASE(magnitude_less_than_zero)
{
EXPECT_EQ(String::formatted("{}", -0.654), "-0.654");