// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: GPL-2.0-or-later //! Writing numbers the way C's printf writes them. //! //! Every output format here was defined by a C program, and consumers have //! parsed its exact output for years. That makes the rounding rule part of //! the format: C's printf rounds according to the floating-point rounding //! mode, which is round-to-nearest with ties to even, where Zig's formatter //! rounds ties away from zero. //! //! It shows up more often than it sounds like it would, because the values //! being printed are not arbitrary. A surface movement report decodes to an //! exact quarter of a knot; a Gilham altitude to an exact multiple of //! twenty-five feet. Ties are the common case, not the rare one. const std = @import("std"); const Io = std.Io; /// Write a float with a fixed number of decimal places, breaking ties to /// even. pub fn fixed(w: *Io.Writer, comptime decimals: comptime_int, value: f64) Io.Writer.Error!void { comptime std.debug.assert(decimals >= 0 and decimals <= 17); const scale = comptime std.math.pow(f64, 10, decimals); const pow10 = comptime blk: { var p: u64 = 1; for (0..decimals) |_| p *= 10; break :blk p; }; // Beyond this the scaled value no longer fits an integer exactly. Nothing // in this program produces such a number, but a NaN or an infinity from a // corrupt decode should print as something rather than trap. if (!std.math.isFinite(value) or @abs(value) * scale >= 1e18) { return w.printValue("d", .{ .precision = decimals }, value, 1); } const scaled = value * scale; const below = @floor(scaled); const rounded = if (scaled - below == 0.5) (if (@mod(below, 2) == 0) below else below + 1) else @round(scaled); // The sign is written separately so that -0.4 prints as "-0.4" rather // than "0.4", which is what C does. if (std.math.signbit(rounded)) try w.writeByte('-'); const magnitude: u64 = @intFromFloat(@abs(rounded)); if (decimals == 0) { try w.print("{d}", .{magnitude}); } else { const format_string = std.fmt.comptimePrint("{{d}}.{{d:0>{d}}}", .{decimals}); try w.print(format_string, .{ magnitude / pow10, magnitude % pow10 }); } } /// A float that formats itself with a fixed number of decimal places, /// breaking ties to even, for use with `{f}` in a format string. /// /// `fixed` writes straight to a writer, which is all most call sites need; /// this is for the ones that want the number in the middle of a sentence /// alongside other arguments. pub fn Fixed(comptime decimals: comptime_int) type { return struct { value: f64, pub fn format(self: @This(), w: *Io.Writer) Io.Writer.Error!void { return fixed(w, decimals, self.value); } }; } /// A float to be written with no decimal places, as C's `%.0f`. pub fn f0(value: f64) Fixed(0) { return .{ .value = value }; } /// A float to be written with one decimal place, as C's `%.1f`. pub fn f1(value: f64) Fixed(1) { return .{ .value = value }; } const testing = std.testing; fn expectFixed(expected: []const u8, comptime decimals: comptime_int, value: f64) !void { var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try fixed(&w, decimals, value); try testing.expectEqualStrings(expected, w.buffered()); } test "ties break to even" { // The cases that actually occur: quarter-knot ground speeds. try expectFixed("4.2", 1, 4.25); try expectFixed("4.4", 1, 4.35); try expectFixed("11.2", 1, 11.25); try expectFixed("0.2", 1, 0.25); try expectFixed("0.4", 1, 0.375); // And the same at zero decimals. try expectFixed("2", 0, 2.5); try expectFixed("4", 0, 3.5); try expectFixed("-2", 0, -2.5); try expectFixed("-4", 0, -3.5); } test "ordinary rounding is unaffected" { try expectFixed("4.3", 1, 4.26); try expectFixed("4.2", 1, 4.24); try expectFixed("-4.3", 1, -4.26); try expectFixed("1.0", 1, 0.96); try expectFixed("100", 0, 99.7); } test "the sign survives a value that rounds to zero" { try expectFixed("-0.0", 1, -0.04); try expectFixed("0.0", 1, 0.04); try expectFixed("-0", 0, -0.4); } test "decimal places" { try expectFixed("3", 0, 3.14159); try expectFixed("3.1", 1, 3.14159); try expectFixed("3.14", 2, 3.14159); try expectFixed("3.142", 3, 3.14159); try expectFixed("3.14159", 5, 3.14159); try expectFixed("52.25720", 5, 52.2572021484375); try expectFixed("0.00100", 5, 0.001); } test "large and unusual values do not trap" { var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try fixed(&w, 1, std.math.inf(f64)); w = .fixed(&buf); try fixed(&w, 1, -std.math.inf(f64)); w = .fixed(&buf); try fixed(&w, 1, std.math.nan(f64)); w = .fixed(&buf); try fixed(&w, 3, 1e30); }