[core] add ability to stringify doubles that are integer with and without trailing ".0"

This commit is contained in:
Konstantin Käfer
2018-10-17 15:52:11 +02:00
parent decbde1616
commit 43687b4781
5 changed files with 18 additions and 12 deletions

View File

@@ -49,9 +49,9 @@ inline std::string toString(uint8_t num) {
return std::to_string(unsigned(num));
}
std::string toString(float);
std::string toString(double);
std::string toString(long double);
std::string toString(float, bool decimal = false);
std::string toString(double, bool decimal = false);
std::string toString(long double, bool decimal = false);
inline std::string toString(std::exception_ptr error) {
assert(error);

View File

@@ -13,12 +13,12 @@ namespace util {
#if !defined(_WINDOWS)
std::string dtoa(double value) {
std::string dtoa(double value, bool decimal) {
std::string data;
data.resize(25);
auto end = rapidjson::internal::dtoa(value, const_cast<char*>(data.data()));
auto length = end - data.data();
if (length >= 3 && end[-1] == '0' && end[-2] == '.') {
if (!decimal && length >= 3 && end[-1] == '0' && end[-2] == '.') {
// Remove trailing ".0" for integers
length -= 2;
}

View File

@@ -6,7 +6,7 @@
namespace mbgl {
namespace util {
std::string dtoa(double value);
std::string dtoa(double value, bool decimal = false);
inline double stod(const std::string& str) {
return ::strtod(str.c_str(), nullptr);

View File

@@ -4,16 +4,17 @@
namespace mbgl {
namespace util {
std::string toString(float num) {
return dtoa(num);
std::string toString(float num, bool decimal) {
return dtoa(num, decimal);
}
std::string toString(double num) {
return dtoa(num);
std::string toString(double num, bool decimal) {
return dtoa(num, decimal);
}
std::string toString(long double num) {
return dtoa(num);
std::string toString(long double num, bool decimal) {
return dtoa(num, decimal);
}
}
} // namespace util

View File

@@ -6,8 +6,13 @@ using namespace mbgl;
TEST(ToString, FloatingPoint) {
EXPECT_EQ("0", util::toString(0.0));
EXPECT_EQ("0.0", util::toString(0.0, true));
EXPECT_EQ("1.33", util::toString(1.33));
EXPECT_EQ("1.33", util::toString(1.33, true));
EXPECT_EQ("-1", util::toString(-1.0));
EXPECT_EQ("-1.0", util::toString(-1.0, true));
EXPECT_EQ("12340000000", util::toString(12340000000.0));
EXPECT_EQ("12340000000.0", util::toString(12340000000.0, true));
EXPECT_EQ("12340000000", util::toString(12340000000.0));
EXPECT_EQ("12340000000.0", util::toString(12340000000.0, true));
}