Skip to content

Commit

Permalink
String::fromNumber gave a wrong result with uint8_t and int8_t values
Browse files Browse the repository at this point in the history
  • Loading branch information
texus committed May 8, 2024
1 parent 151ff95 commit 0414021
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
24 changes: 20 additions & 4 deletions include/TGUI/String.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -321,10 +321,20 @@ TGUI_MODULE_EXPORT namespace tgui
template <typename T>
TGUI_NODISCARD static String fromNumber(T value)
{
std::ostringstream oss;
oss.imbue(std::locale::classic());
oss << value;
return {oss.str()};
// If the value is a floating point then we can't use std::to_string because its result depends on the locale.
// If the value is an 8-bit type (e.g. uint8_t and int8_t) then using std::ostringstream results in the wrong result,
// as it will be interpreted as a character instead of a number.
TGUI_IF_CONSTEXPR (std::is_integral<T>::value)
{
return {std::to_string(value)};
}
else
{
std::ostringstream oss;
oss.imbue(std::locale::classic());
oss << value;
return {oss.str()};
}
}


Expand All @@ -339,6 +349,12 @@ TGUI_MODULE_EXPORT namespace tgui
template <typename T>
TGUI_NODISCARD static String fromNumberRounded(T value, unsigned int decimals)
{
// Precision is ignored by std::ostringstream for integers, so we use std::to_string for integers instead.
// If the value is an 8-bit type (e.g. uint8_t and int8_t) then using std::ostringstream results in the wrong result,
// as it will be interpreted as a character instead of a number. Which is why this separate branch for integers exists.
TGUI_IF_CONSTEXPR (std::is_integral<T>::value)
return {std::to_string(value)};

std::ostringstream oss;
oss.imbue(std::locale::classic());
oss << std::fixed << std::setprecision(static_cast<int>(decimals));
Expand Down
3 changes: 3 additions & 0 deletions tests/String.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1474,13 +1474,16 @@ TEST_CASE("[String]")
REQUIRE(tgui::String::fromNumber(15) == "15");
REQUIRE(tgui::String::fromNumber(-3) == "-3");
REQUIRE(tgui::String::fromNumber(0.5) == "0.5");
REQUIRE(tgui::String::fromNumber(uint8_t(5)) == "5");
}

SECTION("fromNumberRounded")
{
REQUIRE(tgui::String::fromNumberRounded(15.001f, 0) == "15");
REQUIRE(tgui::String::fromNumberRounded(-3.0015f, 3) == "-3.001");
REQUIRE(tgui::String::fromNumberRounded(0.5f, 2) == "0.50");
REQUIRE(tgui::String::fromNumberRounded(15, 2) == "15");
REQUIRE(tgui::String::fromNumberRounded(uint8_t(5), 2) == "5");
}

SECTION("trim")
Expand Down

0 comments on commit 0414021

Please sign in to comment.