AIFeed

Zig gets improved float parser/formatter

Original text(via Hacker News)

Implements the floating point algorithms described in https://research.swtch.com/fp.

I recommend reading the above for an insight into the technical details of how it works. History of this implementation can be found at https://codeberg.org/tiehuis/zig-fp with some more in-depth measurements. I refer to this new implementation as fp going forward.

I have extended the algorithms above to support arbitrary float types in addition to the provided f64 variant. This is also written such that it should be api-compatible, if I've missed anything let me know.

Performance

All build invocations below can run from the zig-fp repo

Generally, fp is ~2x faster than ryu for formatting, and 10-20% faster than eisel-lemire. I've also compared to a zig implementation of zmij which is generally considered the fastest formatting implementation and found it to be generally about the same speed. As a note, the reason I prefer fp to zmij is that the primitives I find more adaptable and I much prefer the same primitives and their usage for both formatting and parsing.

Like the previous implementation, fp is implemented with two backing engines. That is, every float equal or smaller than 64-bits uses the 64-bit engine, and all greater will be backed by a 128-bit engine.

Tests were run on AMD Ryzen 5 5600X 6-Core Processor.

Shortest (f64)


        $ zig build perf -Doptimize=ReleaseFast -- --seed=0 --zmij=true
# mode=scientific precision=null seed=0x0 iters=10000 accumulator=0x1f357339e4ee5c3073c sample=null
  fp: format: 14.49ns, parse: 16.50ns
 std: format: 28.64ns, parse: 19.09ns
zmij: format: 16.51ns
      

Fixed Precision (f64)


        $ zig build perf -Doptimize=ReleaseFast -- --seed=0 --precision=10
# mode=scientific precision=10 seed=0x0 iters=10000 accumulator=0x1f357339e4ee6365fc6 sample=null
  fp: format: 14.34ns, parse: 14.02ns
 std: format: 31.76ns, parse: 16.93ns
      

Large Floats

Floats larger than f64 now also support a faster parse variant. std would always parse these via the slow big int fallback which was a serious performance regression.


        $ zig build perf -Doptimize=ReleaseFast -- --seed=0 --type=f128 --iters=1 --samples=1000
# mode=scientific precision=null seed=0x0 iters=1 accumulator=0x7ce6713de64edddac058d620af60ea10 sample=null
  fp: format: 149.48ns, parse: 120.47ns
 std: format: 220.73ns, parse: 1117267.61ns
      

Binary Size

This is summarized below, for different release types. The f64 engine uses compact tables only for small optimization modes. The f128 engine always uses compact tables.

f64 engine

smallfast
fp10.6KiB23.2KiB
std30.4KiB45.4KiB

f128 engine

smallfast
fp20.9KiB24.4KiB
std30.8KiB43.1KiB

Notable New Features

  • Full precision output is now supported.

        std.debug.format("{d.50}\n", .@as(f64, 123.1));
# std: 123.10000000000000000000000000000000000000000000000000
# fp:  123.09999999999999431565811391919851303100585937500000
      

This uses a new representation of the fallback big integer library. Note that I looked at other techniques such as table-driven approaches like floff. I found though that generally the performance gain was marginal and I preferred the simpler approach here. The table-based approach works well for f64 but is still quite costly for f128 even with super compact tables. The big-int approach as well I could re-use the implementation for fallback parsing for a dual-purpose.

  • Case is now supported as an option when formatting. This currently only applies to special values (e.g. inf, nan). Could extend to exponent specifiers.

Testing

See https://codeberg.org/tiehuis/fp-testcases for floating point test-cases I've compiled. Programs exist in zig-fp which can run against this sample data. Instructions are in the readme.

  • fuzz-tested against reference uscale c implementation
  • exhaustively tested f16, f32 against std
  • fuzz-tested f64, f80, f128 against std

std has been originally fuzz-tested against glibc.

#23942 is still an issue. Simple follow-up to use exact rounding for whole values.

Fixes #20619. Fixes #22779. Fixes #37103. Fixes #37379. Fixes #36208. Fixes #37789.


        stage3 now builds.
      

        Non-hex float output now correctly supports upper-case inf/nan.
      

        - `1.00001e5` - should have rounded down to even
 - `0x0.0p0` - should not print the unnecessary decimal part
 - `0x0.004p-14` - printed unnormalized form. Not strictly wrong, but
   normalized form is better for fixed-precision output.
 - `0.01563` - should have rounded down to even
 - `18014400656965632` - what I think happens here is the result is
   actually considered in exponent form as 1.801440065696563e16 as
   shortest form. When emitting as decimal in std, it would 0-pad to get
   the trailing 0 when the exact repr is actually ...632 which can
   easily be calculated from 2^54 + 2^31. Both however still round-trip.
 - `3.1415` - this is not exact. The exact value is 3.14149996, thus we
   should round down and not up to even.
      

        This should be just as quick if not quicker and makes the mental model
simpler for the caller.
      
@ -70,4 +0,0 @@
// See https://github.com/tiehuis/parse-number-fxx-test-data for a wider-selection of test-data.
test parseFloat {

I rewrote all these tests here: tiehuis/zig-fp@fd82390f15.

They were pretty inconsistent and often testing the same thing multiple ways. The old did pass with the current implementation and the new take from them but try to get a more concise and complete set for sanity checking. I would always expect external testing against a wider range of data for any major changes anyway.

@ -573,3 +573,2 @@
pub const parseFloat = @import ( " fmt/parse_float.zig " ) . parseFloat ;
pub const ParseFloatError = @import ( " fmt/parse_float.zig " ) . ParseFloatError ;
pub const parseFloat = float . parse ;

aside: Not a fan of this alias. Users should prefer directly using float.parse or just making the alias themselves.

I agree, feel free to mark that deprecated in a follow-up.

@ -978,3 +978,1 @@
// libc rounds 1.000005e5 to 1.00000e5 but zig does 1.00001e5.
// In fact, libc doesn't round a lot of 5 cases up when one past the precision point.
try expectFmt ( " f64: 1.00001e5 " , " f64: {e:.5} " , . { @as ( f64 , @as ( f32 , @bitCast ( @as ( u32 , 1203982400 ) ) ) ) } ) ;
try expectFmt ( " f64: 1.00000e5 " , " f64: {e:.5} " , . { @as ( f64 , @as ( f32 , @bitCast ( @as ( u32 , 1203982400 ) ) ) ) } ) ;

To understand this change and the others in this file, I recommend reading this commit: !37793 (commit 9c23ac1031)

@ -0,0 +121,4 @@
/// recommended to bound decimal output with a fixed precision to reduce the required buffer size.
///
/// Asserts s.len is at least min_buffer_size.
pub fn render ( s : [ ] u8 , f : anytype , options : Options ) FormatError ! [ ] const u8 {

aside: I prefer the name format over render here, but not making any changes to the api in this PR.

Agreed, feel free to do that and any other API changes you desire in a follow-up.

@ -0,0 +673,4 @@
return n + 3 ;
}
const digits2 =

This could use digits2 in std.fmt. Just recalled that exists.


        /home/ci/.cache/act/bbc5defc753cafb8/hostexecutor/lib/std/fmt/fp.zig:41:78: error: float value Inf cannot be stored in integer type 'comptime_int'
        const max_exp10: comptime_int = @floor(@log10(std.math.floatMax(F))) + 1;
                                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
      

Looks like this only occurs on targets with 128-bit c_longdouble types using musl: https://git.musl-libc.org/cgit/musl/tree/src/math/log10l.c#n187

Will change this to compute the constant without the builtin.

@tiehuis wrote in #37793 (comment):

Will change this to compute the constant without the builtin.

For tracking purposes, the workaround code should have a comment with a link to a relevant issue or patch.

Will update PR with changes after review/any other changes needed, to batch for ci.

@ -259,1 +259,3 @@
lib/std/fmt/parse_float.zig
lib/std/fmt/fp.zig
lib/std/fmt/fp_bigint.zig
lib/std/fmt/fp_bigint.zig

Duplicate entry.

Fantastic work yet again, @tiehuis.

May I copy your excellent writeup into a devlog for https://ziglang.org/devlog/2026/ ? Or alternately, would you be interested to write one? You only need to edit a single markdown file

@andrewrk wrote in #37793 (comment):

May I copy your excellent writeup into a devlog for https://ziglang.org/devlog/2026/ ? Or alternately, would you be interested to write one? You only need to edit a single markdown file

Happy to write something up for this over the weekend.

The text above was extracted automatically from the source page and may miss images, tables or code blocks. The original is authoritative.

Published by Hacker News
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗