DoxigAlpha

round

Function parameters

Parameters

#
T:type
f:FloatDecimal(T)
precision:usize

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

#
fn round(comptime T: type, f: FloatDecimal(T), mode: RoundMode, precision: usize) FloatDecimal(T) {
    var round_digit: usize = 0;
    var output = f.mantissa;
    var exp = f.exponent;
    const olength = decimalLength(output);

    switch (mode) {
        .decimal => {
            if (f.exponent > 0) {
                round_digit = (olength - 1) + precision + @as(usize, @intCast(f.exponent));
            } else {
                const min_exp_required = @as(usize, @intCast(-f.exponent));
                if (precision + olength > min_exp_required) {
                    round_digit = precision + olength - min_exp_required;
                }
            }
        },
        .scientific => {
            round_digit = 1 + precision;
        },
    }

    if (round_digit < olength) {
        var nlength = olength;
        for (round_digit + 1..olength) |_| {
            output /= 10;
            exp += 1;
            nlength -= 1;
        }

        if (output % 10 >= 5) {
            output /= 10;
            output += 1;
            exp += 1;

            // e.g. 9999 -> 10000
            if (isPowerOf10(output)) {
                output /= 10;
                exp += 1;
            }
        }
    }

    return .{
        .mantissa = output,
        .exponent = exp,
        .sign = f.sign,
    };
}