From cb96ade13ab98986bfd13b10c4972092d212e0ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20W=C3=BChrer?= Date: Tue, 29 Jan 2019 19:01:50 +0100 Subject: [PATCH] format-inl.h: fixing compare double with 0 If compiling with -Wfloat-equal, I get the following error: comparing floating point with == or != is unsafe [-Werror=float-equal] --- include/fmt/format-inl.h | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/include/fmt/format-inl.h b/include/fmt/format-inl.h index 2debe52a..884be94d 100644 --- a/include/fmt/format-inl.h +++ b/include/fmt/format-inl.h @@ -717,11 +717,17 @@ FMT_FUNC gen_digits_params process_specs(const core_format_specs& specs, return params; } +inline bool almost_zero(const double x, const std::size_t ulp) +{ + // Inspired from https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon + return std::abs(x) <= std::numeric_limits::epsilon() * std::abs(x) * static_cast(ulp); +} + template FMT_FUNC typename std::enable_if::type grisu2_format(Double value, buffer& buf, core_format_specs specs) { FMT_ASSERT(value >= 0, "value is negative"); - if (value == 0) { + if (almost_zero(value, 1)) { gen_digits_params params = process_specs(specs, 1, buf); const size_t size = 1; buf[0] = '0';