Skip to content

Commit

Permalink
config: try to fix float locale issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Megamouse committed Feb 24, 2023
1 parent 1445a85 commit 7ab53df
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
17 changes: 16 additions & 1 deletion Utilities/Config.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#include "stdafx.h"
#include "Config.h"
#include "util/types.hpp"

#include "util/yaml.hpp"

#include <charconv>
Expand Down Expand Up @@ -184,6 +183,22 @@ bool try_to_float(f64* out, std::string_view value, f64 min, f64 max)
return true;
}

bool try_to_string(std::string* out, const f64& value)
{
std::array<char, 32> str{};

if (auto [ptr, ec] = std::to_chars(str.data(), str.data() + str.size(), value, std::chars_format::fixed); ec == std::errc())
{
*out = std::string(str.data(), ptr);
return true;
}
else
{
if (out) cfg_log.error("cfg::try_to_string(): could not convert value '%f' to string. error='%s'", value, std::make_error_code(ec).message());
return false;
}
}

bool cfg::try_to_enum_value(u64* out, decltype(&fmt_class_string<int>::format) func, std::string_view value)
{
u64 max = umax;
Expand Down
16 changes: 14 additions & 2 deletions Utilities/Config.h
Original file line number Diff line number Diff line change
Expand Up @@ -384,12 +384,24 @@ namespace cfg

std::string to_string() const override
{
return std::to_string(m_value);
std::string result;
if (try_to_string(&result, m_value))
{
return result;
}

return "0.0";
}

std::string def_to_string() const override
{
return std::to_string(def);
std::string result;
if (try_to_string(&result, def))
{
return result;
}

return "0.0";
}

bool from_string(std::string_view value, bool /*dynamic*/ = false) override
Expand Down
3 changes: 3 additions & 0 deletions Utilities/StrUtil.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ bool try_to_uint64(u64* out, std::string_view value, u64 min, u64 max);
// Convert string to float
bool try_to_float(f64* out, std::string_view value, f64 min, f64 max);

// Convert float to string locale independant
bool try_to_string(std::string* out, const f64& value);

// Get the file extension of a file path ("png", "jpg", etc.)
std::string get_file_extension(const std::string& file_path);

Expand Down

0 comments on commit 7ab53df

Please sign in to comment.