Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

render

Format a floating-point value and write it to buffer. Returns a slice to the buffer containing the string representation.

Full precision is the default. Any full precision float can be reparsed with std.fmt.parseFloat unambiguously.

Scientific mode is recommended generally as the output is more compact and any type can be written in full precision using a buffer of only min_buffer_size.

When printing full precision decimals, use bufferSize to get the required space. It is recommended to bound decimal output with a fixed precision to reduce the required buffer size.

float.render
pub fn render(buf: []u8, value: anytype, options: Options) Error![]const u8

File

lib/std/fmt/float.zig:55

Code

pub fn render(buf: []u8, value: anytype, options: Options) Error![]const u8 {
    const v = switch (@TypeOf(value)) {
        // comptime_float internally is a f128; this preserves precision.
        comptime_float => @as(f128, value),
        else => value,
    };

    const T = @TypeOf(v);
    comptime std.debug.assert(@typeInfo(T) == .float);
    const I = @Int(.unsigned, @bitSizeOf(T));

    const DT = if (@bitSizeOf(T) <= 64) u64 else u128;
    const tables = switch (DT) {
        u64 => if (@import("builtin").mode == .small) &Backend64_TablesSmall else &Backend64_TablesFull,
        u128 => &Backend128_Tables,
        else => unreachable,
    };

    const has_explicit_leading_bit = std.math.floatMantissaBits(T) - std.math.floatFractionalBits(T) != 0;
    const d = binaryToDecimal(DT, @as(I, @bitCast(v)), std.math.floatMantissaBits(T), std.math.floatExponentBits(T), has_explicit_leading_bit, tables);

    return switch (options.mode) {
        .scientific => formatScientific(DT, buf, d, options.precision),
        .decimal => formatDecimal(DT, buf, d, options.precision),
    };
}