Write floats with the shortest digits (Zmij for binary32)

The conversion of Zmij becomes a template on the bit layout of the format,
as upstream Zmij does, and floats (IEEE 754 binary32) use it instead of
Grisu2. The layout of the text (format_buffer()) stays the same; only the
digits change, for 8,821,575 of the 2,139,095,039 positive finite floats:
4,627,275 get one digit fewer (Grisu2 leaves out decimals on the boundary of
the rounding interval), and 4,194,300 take the even one of two equally close
decimals. Every float still reads back as itself. The conversion of doubles
compiles to the same code as before.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
Niels Lohmann committed 2026-11-25 22:45:26 +01:00
1 parent 322063822f
commit 12a1ca5846
7 files changed
+344 -55

No files matched your search

@@ -49,8 +49,8 @@ namespace detail
/*!
@brief implements binary to decimal floating-point conversion: the shortest
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2
algorithm for all other formats.
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 and binary32 numbers, and
the Grisu2 algorithm for all other formats.
The Grisu2 implementation is a slightly modified version of the reference
implementation which may be obtained from
@@ -1397,8 +1397,9 @@ inline char* write_short_decimal(char* first, std::uint64_t digits, int exp) noe
@brief whether FloatType is an IEEE 754 binary64 type (a double, or a long double
that has the same format, as with MSVC and on Apple's Arm CPUs)
These are the types the conversion of Zmij (see zmij.hpp) is used for; all
others (binary32, or a format the library does not know) use Grisu2.
These are the types the conversion of Zmij (see zmij.hpp) is used for with
write_shortest(); binary32 numbers use it with format_buffer(), and all
others (e.g. the 80-bit long double of x87) use Grisu2.
*/
template<typename FloatType>
constexpr bool has_binary64_format() noexcept
@@ -1412,7 +1413,23 @@ constexpr bool has_binary64_format() noexcept
template<typename FloatType>
struct is_binary64 : std::integral_constant<bool, has_binary64_format<FloatType>()> {};
/// a positive finite float (other than binary64): Grisu2 and format_buffer()
/// whether FloatType is an IEEE 754 binary32 type (a float); these use the
/// conversion of Zmij as well
template<typename FloatType>
constexpr bool has_binary32_format() noexcept
{
return std::numeric_limits<FloatType>::is_iec559
&& std::numeric_limits<FloatType>::digits == 24
&& std::numeric_limits<FloatType>::max_exponent == 128
&& sizeof(FloatType) == sizeof(std::uint32_t);
}
/// the conversion for a floating-point type: 0 for Grisu2, 1 for Zmij on
/// binary64, 2 for Zmij on binary32
template<typename FloatType>
struct float_conversion : std::integral_constant < int, (has_binary64_format<FloatType>() ? 1 : 0) + (has_binary32_format<FloatType>() ? 2 : 0) > {};
/// a positive finite float (other than binary64 and binary32): Grisu2 and format_buffer()
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
@@ -1466,32 +1483,79 @@ char* write_positive_zmij(char* first, const char* last, FloatType value)
return first + len;
}
/// a positive finite binary32 number: the shortest digits (Zmij), laid out by
/// format_buffer() as the digits of Grisu2 were (only the digits differ: Grisu2
/// leaves out a decimal on the boundary of the rounding interval and may take
/// the other one of two equally close decimals)
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive_zmij_binary32(char* first, const char* last, FloatType value)
{
static_assert(has_binary32_format<FloatType>(),
"internal error: this conversion of Zmij needs IEEE 754 binary32 numbers");
const zmij::shortest_decimal d = zmij::to_shortest_of<zmij::binary32_format>(bit_cast<std::uint32_t>(value));
std::uint64_t digits = d.has_digit ? (d.integral * 10) + d.digit : d.integral;
int decimal_exponent = d.has_digit ? d.exponent : d.exponent + 1;
while (digits % 10 == 0)
{
digits /= 10;
++decimal_exponent;
}
// at most 9 digits (max_digits10), written from the end
std::array<char, 9> buf; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read
std::size_t start = buf.size();
do
{
buf[--start] = static_cast<char>('0' + (digits % 10));
digits /= 10;
}
while (digits != 0);
const auto len = static_cast<int>(buf.size() - start);
JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
JSON_ASSERT(last - first >= 2 + 3 + std::numeric_limits<FloatType>::max_digits10);
static_cast<void>(last); // (only used in the assertions)
std::memcpy(first, buf.data() + start, static_cast<std::size_t>(len));
// as write_positive_grisu2()
return format_buffer(first, len, decimal_exponent, -4, std::numeric_limits<FloatType>::digits10);
}
/// a positive finite float of a format without Zmij: Grisu2
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 0> /*grisu2*/)
{
return write_positive_grisu2(first, last, value);
}
/// a positive finite binary64 number: Zmij (as a long double has the format of
/// a double here, its bits are those of the double of the same value)
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value, std::true_type /*is_binary64*/)
char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 1> /*binary64*/)
{
return write_positive_zmij(first, last, value);
}
/// a positive finite float of any other format: Grisu2
/// a positive finite binary32 number: Zmij
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value, std::false_type /*is_binary64*/)
char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 2> /*binary32*/)
{
return write_positive_grisu2(first, last, value);
return write_positive_zmij_binary32(first, last, value);
}
/// a positive finite float: Zmij for binary64 numbers, Grisu2 otherwise
/// a positive finite float: Zmij for binary64 and binary32 numbers, Grisu2 otherwise
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value)
{
return write_positive(first, last, value, is_binary64<FloatType> {});
return write_positive(first, last, value, float_conversion<FloatType> {});
}
} // namespace dtoa_impl
+31 -10
View File
@@ -160,22 +160,37 @@ struct shortest_decimal
bool has_digit; ///< whether the shortest decimal is integral * 10 + digit
};
/// The shortest decimal in the rounding interval of a positive finite double
/// given by its bits, the closest one if there are several (to_decimal of
/// Zmij, which keeps the last digit apart: the 15 or 16 digits before it can be
/// converted without a multiplication by 10 first). Always inlined: GCC
/// otherwise calls it, and its result goes through memory.
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept
/// the bit layout of an IEEE 754 binary format: SigBits significand bits
/// (without the implicit bit) below ExpBits exponent bits
template<int SigBits, int ExpBits>
struct binary_format
{
static constexpr unsigned sig_bits = SigBits;
static constexpr unsigned exp_mask = (1u << static_cast<unsigned>(ExpBits)) - 1u;
static constexpr int exp_offset = (1 << (ExpBits - 1)) - 1 + SigBits; // the bias plus the significand bits
};
using binary64_format = binary_format<52, 11>;
using binary32_format = binary_format<23, 8>;
/// The shortest decimal in the rounding interval of a positive finite number of
/// the format Format given by its bits, the closest one if there are several
/// (to_decimal of Zmij, which keeps the last digit apart: the 15 or 16 digits
/// of a normal double before it, 6 or 7 of a float, can be converted without a
/// multiplication by 10 first). As in Zmij, the same computation serves both
/// formats; only the bit layout differs. Always inlined: GCC otherwise calls
/// it, and its result goes through memory.
template<typename Format>
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest_of(std::uint64_t bits) noexcept
{
constexpr int extra_shift = 9;
const auto raw_exp = static_cast<int>((bits >> 52u) & 0x7FFu);
std::uint64_t bin_sig = bits & ((std::uint64_t{1} << 52u) - 1);
const auto raw_exp = static_cast<int>((bits >> Format::sig_bits) & Format::exp_mask);
std::uint64_t bin_sig = bits & ((std::uint64_t{1} << Format::sig_bits) - 1);
// a power of two has a narrower interval below (except the smallest normal)
const bool regular = bin_sig != 0 || raw_exp <= 1;
const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - 1075;
const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - Format::exp_offset;
if (raw_exp != 0)
{
bin_sig |= std::uint64_t{1} << 52u;
bin_sig |= std::uint64_t{1} << Format::sig_bits;
}
// floor(log10(2^bin_exp)), or floor(log10(3/4 * 2^bin_exp)) for the irregular case
const int dec_exp = ((bin_exp * 315653) - (regular ? 0 : 131072)) >> 20;
@@ -217,6 +232,12 @@ JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexc
return shortest_decimal{integral, dec_exp, static_cast<unsigned char>(digit), !round_up && !round_down};
}
/// to_shortest_of() for a double given by its bits
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept
{
return to_shortest_of<binary64_format>(bits);
}
} // namespace zmij
} // namespace detail
NLOHMANN_JSON_NAMESPACE_END