Skip to content

Commit fd5e514

Browse files
authored
Merge pull request #337 from scratchcpp/string_to_double_locale
Fix #331: Fix string conversion issues caused by the locale
2 parents e8b7bf5 + c55eff7 commit fd5e514

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

include/scratchcpp/value.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -799,8 +799,15 @@ class LIBSCRATCHCPP_EXPORT Value
799799
if (ok)
800800
*ok = true;
801801

802+
// Set locale to C to avoid conversion issues
803+
std::string oldLocale = std::setlocale(LC_NUMERIC, nullptr);
804+
std::setlocale(LC_NUMERIC, "C");
805+
802806
double ret = std::stod(*stringPtr);
803807

808+
// Restore old locale
809+
std::setlocale(LC_NUMERIC, oldLocale.c_str());
810+
804811
if (customStr)
805812
delete stringPtr;
806813

test/scratch_classes/value_test.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,24 @@ TEST(ValueTest, StdStringConstructor)
135135
ASSERT_FALSE(v.isString());
136136
}
137137

138+
{
139+
std::string oldLocale = std::setlocale(LC_NUMERIC, nullptr);
140+
std::setlocale(LC_NUMERIC, "sk_SK.UTF-8");
141+
142+
Value v(std::string("532.15"));
143+
144+
std::setlocale(LC_NUMERIC, oldLocale.c_str());
145+
146+
ASSERT_EQ(v.toString(), "532.15");
147+
ASSERT_EQ(v.type(), Value::Type::Double);
148+
ASSERT_FALSE(v.isInfinity());
149+
ASSERT_FALSE(v.isNegativeInfinity());
150+
ASSERT_FALSE(v.isNaN());
151+
ASSERT_TRUE(v.isNumber());
152+
ASSERT_FALSE(v.isBool());
153+
ASSERT_FALSE(v.isString());
154+
}
155+
138156
{
139157
Value v(std::string("1 2 3"));
140158
ASSERT_EQ(v.toString(), "1 2 3");

0 commit comments

Comments
 (0)