From 5e53a690ace8dce64f72a5a734def8e832f6b7d3 Mon Sep 17 00:00:00 2001 From: Idan Horowitz Date: Sat, 19 Jun 2021 17:00:31 +0300 Subject: [PATCH] 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" --- AK/Format.cpp | 11 ++++++++--- AK/Format.h | 1 + Tests/AK/TestFormat.cpp | 6 ++++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/AK/Format.cpp b/AK/Format.cpp index 82047a8673..5385d5552f 100644 --- a/AK/Format.cpp +++ b/AK/Format.cpp @@ -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(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::max(), fill); @@ -623,7 +628,7 @@ void Formatter::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::format(FormatBuilder& builder, float value) { diff --git a/AK/Format.h b/AK/Format.h index cae81e821a..3eb562752d 100644 --- a/AK/Format.h +++ b/AK/Format.h @@ -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, diff --git a/Tests/AK/TestFormat.cpp b/Tests/AK/TestFormat.cpp index 9e0aad7810..50ddde2f47 100644 --- a/Tests/AK/TestFormat.cpp +++ b/Tests/AK/TestFormat.cpp @@ -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");