Skip to content

Commit

Permalink
AK: Fix printing of negative FixedPoint values
Browse files Browse the repository at this point in the history
Fixes #17514 by comparing to 0 before truncating the fractional part.
  • Loading branch information
nico authored and awesomekling committed Feb 18, 2023
1 parent 13f5aa8 commit a30e364
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 2 deletions.
6 changes: 5 additions & 1 deletion AK/FixedPoint.h
Original file line number Diff line number Diff line change
Expand Up @@ -420,10 +420,14 @@ struct Formatter<FixedPoint<precision, Underlying>> : StandardFormatter {
m_width = m_width.value_or(0);
m_precision = m_precision.value_or(6);

bool is_negative = false;
if constexpr (IsSigned<Underlying>)
is_negative = value < 0;

i64 integer = value.ltrunk();
constexpr u64 one = static_cast<Underlying>(1) << precision;
u64 fraction_raw = value.raw() & (one - 1);
return builder.put_fixed_point(integer, fraction_raw, one, base, upper_case, m_zero_pad, m_align, m_width.value(), m_precision.value(), m_fill, m_sign_mode, real_number_display_mode);
return builder.put_fixed_point(is_negative, integer, fraction_raw, one, base, upper_case, m_zero_pad, m_align, m_width.value(), m_precision.value(), m_fill, m_sign_mode, real_number_display_mode);
}
};

Expand Down
2 changes: 1 addition & 1 deletion AK/Format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,7 @@ ErrorOr<void> FormatBuilder::put_i64(
}

ErrorOr<void> FormatBuilder::put_fixed_point(
bool is_negative,
i64 integer_value,
u64 fraction_value,
u64 fraction_one,
Expand All @@ -373,7 +374,6 @@ ErrorOr<void> FormatBuilder::put_fixed_point(
StringBuilder string_builder;
FormatBuilder format_builder { string_builder };

bool is_negative = integer_value < 0;
if (is_negative)
integer_value = -integer_value;

Expand Down
1 change: 1 addition & 0 deletions AK/Format.h
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ class FormatBuilder {
SignMode sign_mode = SignMode::OnlyIfNeeded);

ErrorOr<void> put_fixed_point(
bool is_negative,
i64 integer_value,
u64 fraction_value,
u64 fraction_one,
Expand Down
3 changes: 3 additions & 0 deletions Tests/AK/TestFixedPoint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -155,4 +155,7 @@ TEST_CASE(formatter)
EXPECT_EQ(DeprecatedString::formatted("{}", FixedPoint<16>(0.003)), "0.00299"sv);
EXPECT_EQ(DeprecatedString::formatted("{}", FixedPoint<16>(0.0004)), "0.000396"sv);
EXPECT_EQ(DeprecatedString::formatted("{}", FixedPoint<16>(0.0000000005)), "0"sv);
EXPECT_EQ(DeprecatedString::formatted("{}", FixedPoint<16>(-0.1)), "-0.099991"sv);
EXPECT_EQ(DeprecatedString::formatted("{}", FixedPoint<16>(-0.02)), "-0.01999"sv);
EXPECT_EQ(DeprecatedString::formatted("{}", FixedPoint<16>(-0.0000000005)), "0"sv);
}

0 comments on commit a30e364

Please sign in to comment.