diff --git a/README.rst b/README.rst index 5e0b4549..2c1e31ca 100644 --- a/README.rst +++ b/README.rst @@ -25,7 +25,8 @@ Features reported using exceptions. * Ease of use: small self-contained code base, no external dependencies, permissive BSD `license`_. -* `Portability`_ and support for older compilers. +* `Portability`_ with consistent output across platforms and support + for older compilers. Examples -------- diff --git a/format.cc b/format.cc index 94b3aca2..bbc9b423 100644 --- a/format.cc +++ b/format.cc @@ -141,7 +141,7 @@ int signbit(double value) { if (value < 0) return 1; if (value == value) return 0; int dec = 0, sign = 0; - ecvt(value, 0, &dec, &sign); + _ecvt(value, 0, &dec, &sign); return sign; } #endif @@ -337,6 +337,21 @@ void Formatter::FormatDouble(T value, const FormatSpec &spec, int precision) { return; } + if (isinf(value)) { + // Format infinity ourselves because sprintf's output is not consistent + // across platforms. + std::size_t size = 4; + const char *inf = upper ? " INF" : " inf"; + if (!sign) { + --size; + ++inf; + } + char *out = FormatString(inf, size, spec); + if (sign) + *out = sign; + return; + } + size_t offset = buffer_.size(); unsigned width = spec.width; if (sign) { diff --git a/format_test.cc b/format_test.cc index cde7455e..0e3a734d 100644 --- a/format_test.cc +++ b/format_test.cc @@ -774,10 +774,6 @@ TEST(FormatterTest, FormatDouble) { sprintf(buffer, "%E", 392.65); EXPECT_EQ(buffer, str(Format("{0:E}") << 392.65)); EXPECT_EQ("+0000392.6", str(Format("{0:+010.4g}") << 392.65)); - double inf = std::numeric_limits::infinity(); - EXPECT_EQ("inf", str(Format("{}") << inf)); - EXPECT_EQ("-inf", str(Format("{}") << -inf)); - EXPECT_EQ("INF", str(Format("{:F}") << inf)); } TEST(FormatterTest, FormatNaN) { @@ -792,6 +788,18 @@ TEST(FormatterTest, FormatNaN) { EXPECT_EQ(" nan", str(Format("{:>7}") << nan)); } +TEST(FormatterTest, FormatInfinity) { + double inf = std::numeric_limits::infinity(); + EXPECT_EQ("inf", str(Format("{}") << inf)); + EXPECT_EQ("+inf", str(Format("{:+}") << inf)); + EXPECT_EQ("-inf", str(Format("{}") << -inf)); + EXPECT_EQ(" inf", str(Format("{: }") << inf)); + EXPECT_EQ("INF", str(Format("{:F}") << inf)); + EXPECT_EQ("inf ", str(Format("{:<7}") << inf)); + EXPECT_EQ(" inf ", str(Format("{:^7}") << inf)); + EXPECT_EQ(" inf", str(Format("{:>7}") << inf)); +} + TEST(FormatterTest, FormatLongDouble) { EXPECT_EQ("0", str(Format("{0:}") << 0.0l)); EXPECT_EQ("0.000000", str(Format("{0:f}") << 0.0l));