Skip to content

std.fmt: Fix incorrect behavior with large floating point integers. #11380

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/std/fmt.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2299,6 +2299,8 @@ test "float.decimal" {
try expectFmt("f64: 0.00000", "f64: {d:.5}", .{@as(f64, 1.40130e-45)});
try expectFmt("f64: 0.00000", "f64: {d:.5}", .{@as(f64, 9.999960e-40)});
try expectFmt("f64: 10000000000000.00", "f64: {d:.2}", .{@as(f64, 9999999999999.999)});
try expectFmt("f64: 10000000000000000000000000000000000000", "f64: {d}", .{@as(f64, 1e37)});
try expectFmt("f64: 100000000000000000000000000000000000000", "f64: {d}", .{@as(f64, 1e38)});
}

test "float.libc.sanity" {
Expand Down
7 changes: 6 additions & 1 deletion lib/std/fmt/errol.zig
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,10 @@ fn errol3u(val: f64, buffer: []u8) FloatDecimal {
} else if (val >= 16.0 and val < 9.007199254740992e15) {
return errolFixed(val, buffer);
}
return errolSlow(val, buffer);
}

fn errolSlow(val: f64, buffer: []u8) FloatDecimal {
// normalize the midpoint

const e = math.frexp(val).exponent;
Expand Down Expand Up @@ -336,7 +339,9 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal {
var buf_index = u64toa(m64, buffer) - 1;

if (mi != 0) {
buffer[buf_index - 1] += @boolToInt(buffer[buf_index] >= '5');
const round_up = buffer[buf_index] >= '5';
if (buf_index == 0 or (round_up and buffer[buf_index - 1] == '9')) return errolSlow(val, buffer);
buffer[buf_index - 1] += @boolToInt(round_up);
} else {
buf_index += 1;
}
Expand Down