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.
Function parameters
Parameters
Type definitions in this namespace
Types
Returns the minimum buffer size needed to print every float of a specific type and format.
Functions
- bufferSize
- Returns the minimum buffer size needed to print every float of a specific type and format.
- render
- Format a floating-point value and write it to buffer.
- formatScientific
- Write a FloatDecimal to a buffer in scientific form.
- formatDecimal
- Write a FloatDecimal to a buffer in decimal form.
- binaryToDecimal
- Convert a binary float representation to decimal.
Error sets in this namespace
Error Sets
Any buffer used for `format` must be at least this large.
Values
- min_buffer_size
- Any buffer used for `format` must be at least this large.
Source
Implementation
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 = @Type(.{ .int = .{ .signedness = .unsigned, .bits = @bitSizeOf(T) } });
const DT = if (@bitSizeOf(T) <= 64) u64 else u128;
const tables = switch (DT) {
u64 => if (@import("builtin").mode == .ReleaseSmall) &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),
};
}