From c55eff73e1e4c883795754c0707a8057b06d395d Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Sat, 25 Nov 2023 18:18:54 +0100 Subject: [PATCH] fix #331: Use the C locale during string conversion --- include/scratchcpp/value.h | 7 +++++++ test/scratch_classes/value_test.cpp | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/include/scratchcpp/value.h b/include/scratchcpp/value.h index 3dd86335..5186748f 100644 --- a/include/scratchcpp/value.h +++ b/include/scratchcpp/value.h @@ -799,8 +799,15 @@ class LIBSCRATCHCPP_EXPORT Value if (ok) *ok = true; + // Set locale to C to avoid conversion issues + std::string oldLocale = std::setlocale(LC_NUMERIC, nullptr); + std::setlocale(LC_NUMERIC, "C"); + double ret = std::stod(*stringPtr); + // Restore old locale + std::setlocale(LC_NUMERIC, oldLocale.c_str()); + if (customStr) delete stringPtr; diff --git a/test/scratch_classes/value_test.cpp b/test/scratch_classes/value_test.cpp index 65f0e9e8..d2c2c71a 100644 --- a/test/scratch_classes/value_test.cpp +++ b/test/scratch_classes/value_test.cpp @@ -135,6 +135,24 @@ TEST(ValueTest, StdStringConstructor) ASSERT_FALSE(v.isString()); } + { + std::string oldLocale = std::setlocale(LC_NUMERIC, nullptr); + std::setlocale(LC_NUMERIC, "sk_SK.UTF-8"); + + Value v(std::string("532.15")); + + std::setlocale(LC_NUMERIC, oldLocale.c_str()); + + ASSERT_EQ(v.toString(), "532.15"); + ASSERT_EQ(v.type(), Value::Type::Double); + ASSERT_FALSE(v.isInfinity()); + ASSERT_FALSE(v.isNegativeInfinity()); + ASSERT_FALSE(v.isNaN()); + ASSERT_TRUE(v.isNumber()); + ASSERT_FALSE(v.isBool()); + ASSERT_FALSE(v.isString()); + } + { Value v(std::string("1 2 3")); ASSERT_EQ(v.toString(), "1 2 3");