Skip to content

Printing a float with high precision is incorrect #22779

Open
@abgros

Description

@abgros

Zig Version

0.14.0-dev.3047+3a4bb47fe

Steps to Reproduce and Observed Behavior

Run the following:

const std = @import("std");

pub fn main() void {
    const a: f64 = 0.1;
    const b: f64 = 0.2;
    std.debug.print("{d:.52}\n", .{a + b});
}

The result is 0.3000000000000000400000000000000000000000000000000000 which doesn't make any sense. It looks like Zig has clipped everything past the first 4.

Expected Behavior

The correct result is 0.3000000000000000444089209850062616169452667236328125, which is the exact value of the float with bit pattern 0x3fd3333333333334. This result can be confirmed in other programming languages, such as JavaScript and Python.

(0.1 + 0.2).toFixed(52)
print("{:.52f}".format(0.1 + 0.2))

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behaviorstandard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions