Programming Search⌘K

Taskintro

Format a number with fixed decimals

Also called fixed decimals, fixed-point notation, round to 2 decimals, two decimal places, %.2f, {:.2f}, toFixed, F2 format, decimal places, format a float, round for display.

Write a floating-point number with exactly n digits after the decimal point, with %.2f, toFixed, F2 or {:.2}. The function rounds the stored binary value, so 2.675 gives 2.67.

Task

Write a number with a fixed count of digits after the decimal point, for example a price with 2 decimals or a measure with 3. The Rosetta Code task Formatted numeric output asks a similar question: "Express a number in decimal as a fixed-length string with leading zeros"1.

The function fixed(x, digits) returns x in decimal notation, without an exponent, with exactly digits digits after the point. The point is a dot on each computer.

x digits Result
3.14159 2 3.14
1.0 3 1.000
1234.5678 2 1234.57
123.456 0 123

A floating-point number is a binary fraction, so most decimal numbers are stored as a value that is a little more or a little less. For 0.1, the Python tutorial shows that "the exact number stored in the computer is equal to the decimal value 0.1000000000000000055511151231257827021181583404541015625"2. The function rounds this stored value, not the text that was written in the program. So fixed(2.675, 2) is 2.67: the stored value is a little less than 2.675.

Solutions

Language Expression
Python f"{x:.{digits}f}"
JavaScript, TypeScript x.toFixed(digits)
Java new BigDecimal(x).setScale(digits, RoundingMode.HALF_EVEN).toPlainString()
C# x.ToString("F" + digits, CultureInfo.InvariantCulture)
Go strconv.FormatFloat(x, 'f', digits, 64)
Rust format!("{x:.digits$}")
C snprintf(out, size, "%.*f", digits, x)
C++ std::format("{:.{}f}", x, digits)
Bash awk with printf "%.*f"
  • Python. The type f is "Fixed-point notation. For a given precision p, formats the number as a decimal number with exactly p digits following the decimal point"3. Python does not use the locale here.
  • JavaScript. toFixed "returns a string representation of a number without using exponential notation and with exactly digits digits after the decimal point"4. It rounds the stored value: MDN shows that (2.55).toFixed(1) gives '2.5', because the "closest representable float is lower"4. For 1e21 and more, it uses exponential notation.
  • TypeScript. The same as JavaScript.
  • Java. String.format("%.2f", x) does not round the stored value. Its documentation says that the value "will be rounded using the round half up algorithm"5, and it rounds the short decimal text of Double.toString. The solution uses BigDecimal: the constructor gives "the exact decimal representation of the double's binary floating-point value"6, and setScale rounds it.
  • C#. The format F gives "Integral and decimal digits with optional negative sign"7. The result "reflects a number that is rounded to a representable result nearest to the infinitely precise result"7. The culture gives the decimal separator, so the solution passes the invariant culture.
  • Go. With %f, "precision sets the number of places after the decimal"8. strconv.FormatFloat with the format 'f' takes the count of digits as an argument.
  • Rust. For a float, the precision "indicates how many digits after the decimal point should be printed"9. .digits$ takes the count from a variable.
  • C. %.*f takes the precision from an argument. "The precision specifies the number of decimal places, trailing zeros will be written if necessary"10. The decimal point comes from the locale, and the default C locale gives a dot.
  • C++. The type f "Produces the output as if by calling std::to_chars(first, last, value, std::chars_format::fixed, precision)"11. {:.{}f} takes the precision from the next argument.
  • Bash. The shell printf reads the number as a long double, which is not the same value as a double (see Pitfalls). The solution calls awk, which uses a double.

The Python solution, with the stored value of 2.675:

from decimal import Decimal


def fixed(x, digits):
    return f"{x:.{digits}f}"


print(fixed(3.14159, 2), fixed(1.0, 3), fixed(123.456, 0))
print(fixed(0.1, 20))
print(Decimal(2.675))
print(fixed(2.675, 2), round(2.675, 2))
print(fixed(0.125, 2), fixed(2.5, 0))
Output
3.14 1.000 123
0.10000000000000000555
2.67499999999999982236431605997495353221893310546875
2.67 2.67
0.12 2

The last line shows a value that is exactly halfway: 0.125 and 2.5 are stored exactly. Python rounds a tie to the even digit.

Edge cases

  • No decimals. With digits 0, there is no decimal point: fixed(123.456, 0) is 123.
  • A stored value under the half. 2.675 and 1.005 give 2.67 and 1.00, because the stored values are a little less than the written values.
  • Many digits. fixed(0.1, 20) is 0.10000000000000000555. The digits after the 17th show the binary value.
  • Large numbers. 1e20 with 2 decimals is 100000000000000000000.00, with no exponent. In JavaScript, toFixed uses an exponent from 1e21.
  • Negative numbers. The minus sign is first: fixed(-1.234, 1) is -1.2.
  • An integer value. 42.0 with 2 decimals is 42.00.

Pitfalls

  • Java rounds the decimal text. String.format rounds the short text of the number, so it does not give the same result as the other languages:

This code runs but gives a wrong answer on purpose.

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        System.out.println(String.format(Locale.ROOT, "%.2f", 2.675));
        System.out.println(String.format(Locale.ROOT, "%.2f", 1.005));
        System.out.println(String.format(Locale.ROOT, "%.20f", 0.1));
        System.out.println(new BigDecimal(2.675).setScale(2, RoundingMode.HALF_EVEN).toPlainString());
    }
}
Output
2.68
1.01
0.10000000000000000000
2.67

Both results can be correct for a program, but a program that compares its output with a program in another language must use one rule.

  • The shell printf. Bash reads the number as a long double, so the extra digits are not those of a double:

This code runs but gives a wrong answer on purpose.

LC_NUMERIC=C printf '%.20f\n' 0.1
LC_ALL=C awk 'BEGIN { printf "%.20f\n", 0.1 }'
Output
0.10000000000000000000
0.10000000000000000555
  • Ties are not the same in all languages. When the stored value is exactly halfway, Python rounds to the even digit (see the Python solution), and JavaScript toFixed takes the larger value:
console.log((0.125).toFixed(2), (2.5).toFixed(0), (-2.5).toFixed(0));
Output
0.13 3 -3
  • Formatting is not rounding the value. fixed returns text. To compute with a rounded value, round the number, or use a decimal type for money.
  • The locale. C# ToString("F2"), Java String.format without a locale and C printf after setlocale use the decimal separator of the locale. In Germany, the result is 3,14.

Code

The build runs the native tests of each language in a pinned toolchain.

fixed.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.


def fixed(x: float, digits: int) -> str:
    """Return x with exactly digits digits after the decimal point. The
    exact binary value of x is rounded."""
    return f"{x:.{digits}f}"


if __name__ == "__main__":
    print(fixed(3.14159, 2))
    print(fixed(2.675, 2))
test_fixed.py 26 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

import pytest

from fixed import fixed

CASES = [
    ("pi-two", 3.14159, 2, "3.14"),
    ("pad-zeros", 1.0, 3, "1.000"),
    ("round-up", 1234.5678, 2, "1234.57"),
    ("zero-digits", 123.456, 0, "123"),
    ("float-error", 0.30000000000000004, 2, "0.30"),
    ("negative", -1.234, 1, "-1.2"),
    ("rounds-to-zero", 0.0049, 2, "0.00"),
    ("stored-below-2-675", 2.675, 2, "2.67"),
    ("stored-below-1-005", 1.005, 2, "1.00"),
    ("large", 1e+20, 2, "100000000000000000000.00"),
    ("many-digits", 0.1, 20, "0.10000000000000000555"),
    ("integer-value", 42.0, 2, "42.00"),
]


@pytest.mark.parametrize(("name", "x", "digits", "want"), CASES, ids=[c[0] for c in CASES])
def test_fixed(name, x, digits, want):
    assert fixed(x, digits) == want
fixed.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

#ifndef FIXED_HPP
#define FIXED_HPP

#include <format>
#include <string>

// Returns x with exactly digits digits after the decimal point. std::format
// rounds the exact binary value of x and does not use the locale.
inline std::string fixed(double x, int digits) {
    return std::format("{:.{}f}", x, digits);
}

#endif
test_fixed.cpp 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

#include <cstdio>

#include "fixed.hpp"

namespace {

struct test_case {
    const char* name;
    double x;
    int digits;
    const char* want;
};

const test_case cases[] = {
    {"pi-two", 3.14159, 2, "3.14"},
    {"pad-zeros", 1.0, 3, "1.000"},
    {"round-up", 1234.5678, 2, "1234.57"},
    {"zero-digits", 123.456, 0, "123"},
    {"float-error", 0.30000000000000004, 2, "0.30"},
    {"negative", -1.234, 1, "-1.2"},
    {"rounds-to-zero", 0.0049, 2, "0.00"},
    {"stored-below-2-675", 2.675, 2, "2.67"},
    {"stored-below-1-005", 1.005, 2, "1.00"},
    {"large", 1e+20, 2, "100000000000000000000.00"},
    {"many-digits", 0.1, 20, "0.10000000000000000555"},
    {"integer-value", 42.0, 2, "42.00"},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const std::string got = fixed(c.x, c.digits);
        if (got != c.want) {
            std::printf("FAIL %s: got \"%s\"\n", c.name, got.c_str());
            ++failures;
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Fixed.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

import java.math.BigDecimal;
import java.math.RoundingMode;

/** A number with a fixed count of decimals. */
public final class Fixed {
    private Fixed() {}

    /**
     * Returns x with exactly digits digits after the decimal point. new
     * BigDecimal(x) is the exact binary value of x, so the result is the same
     * as in C or Python. String.format rounds the short decimal text of x
     * instead, and gives 2.68 for 2.675.
     */
    public static String fixed(double x, int digits) {
        return new BigDecimal(x).setScale(digits, RoundingMode.HALF_EVEN).toPlainString();
    }

    public static void main(String[] args) {
        System.out.println(fixed(3.14159, 2));
        System.out.println(fixed(2.675, 2));
    }
}
FixedTest.java 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class FixedTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("pi-two", 3.14159, 2, "3.14"),
                Arguments.of("pad-zeros", 1.0, 3, "1.000"),
                Arguments.of("round-up", 1234.5678, 2, "1234.57"),
                Arguments.of("zero-digits", 123.456, 0, "123"),
                Arguments.of("float-error", 0.30000000000000004, 2, "0.30"),
                Arguments.of("negative", -1.234, 1, "-1.2"),
                Arguments.of("rounds-to-zero", 0.0049, 2, "0.00"),
                Arguments.of("stored-below-2-675", 2.675, 2, "2.67"),
                Arguments.of("stored-below-1-005", 1.005, 2, "1.00"),
                Arguments.of("large", 1e+20, 2, "100000000000000000000.00"),
                Arguments.of("many-digits", 0.1, 20, "0.10000000000000000555"),
                Arguments.of("integer-value", 42.0, 2, "42.00")
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void fixed(String name, double x, int digits, String want) {
        assertEquals(want, Fixed.fixed(x, digits));
    }
}
fixed.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

#include "fixed.h"

#include <stdio.h>

int fixed(char *out, size_t size, double x, int digits) {
    return snprintf(out, size, "%.*f", digits, x);
}
fixed.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

#ifndef FIXED_H
#define FIXED_H

#include <stddef.h>

// Writes x with exactly digits digits after the decimal point into out.
// Returns the length of the full result, as snprintf does. If the result is
// size or more, the text was cut to fit the buffer. The decimal point comes
// from the locale, and the C locale gives a dot.
int fixed(char *out, size_t size, double x, int digits);

#endif
test_fixed.c 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

#include "fixed.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test_case {
    const char *name;
    double x;
    int digits;
    const char *want;
};

static const struct test_case cases[] = {
    {"pi-two", 3.14159, 2, "3.14"},
    {"pad-zeros", 1.0, 3, "1.000"},
    {"round-up", 1234.5678, 2, "1234.57"},
    {"zero-digits", 123.456, 0, "123"},
    {"float-error", 0.30000000000000004, 2, "0.30"},
    {"negative", -1.234, 1, "-1.2"},
    {"rounds-to-zero", 0.0049, 2, "0.00"},
    {"stored-below-2-675", 2.675, 2, "2.67"},
    {"stored-below-1-005", 1.005, 2, "1.00"},
    {"large", 1e+20, 2, "100000000000000000000.00"},
    {"many-digits", 0.1, 20, "0.10000000000000000555"},
    {"integer-value", 42.0, 2, "42.00"},
};

int main(void) {
    int failures = 0;
    char buf[64];
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        int n = fixed(buf, sizeof buf, c->x, c->digits);
        if (n != (int)strlen(c->want) || strcmp(buf, c->want) != 0) {
            printf("FAIL %s: got \"%s\"\n", c->name, buf);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Fixed.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

using System.Globalization;

/// <summary>A number with a fixed count of decimals.</summary>
public static class Fixed
{
    /// <summary>
    /// Returns x with exactly digits digits after the decimal point. The
    /// format F rounds the exact binary value of x, and the invariant culture
    /// gives a dot.
    /// </summary>
    public static string Format(double x, int digits) =>
        x.ToString("F" + digits.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
}
FixedTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

using Xunit;

public sealed class FixedTests
{
    public static TheoryData<string, double, int, string> Cases => new()
    {
        { "pi-two", 3.14159, 2, "3.14" },
        { "pad-zeros", 1.0, 3, "1.000" },
        { "round-up", 1234.5678, 2, "1234.57" },
        { "zero-digits", 123.456, 0, "123" },
        { "float-error", 0.30000000000000004, 2, "0.30" },
        { "negative", -1.234, 1, "-1.2" },
        { "rounds-to-zero", 0.0049, 2, "0.00" },
        { "stored-below-2-675", 2.675, 2, "2.67" },
        { "stored-below-1-005", 1.005, 2, "1.00" },
        { "large", 1e+20, 2, "100000000000000000000.00" },
        { "many-digits", 0.1, 20, "0.10000000000000000555" },
        { "integer-value", 42.0, 2, "42.00" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Format(string name, double x, int digits, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Fixed.Format(x, digits));
    }
}
fixed.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

/**
 * Returns x with exactly digits digits after the decimal point. toFixed
 * rounds the exact binary value of x. It uses an exponent for 1e21 and more.
 */
export function fixed(x, digits) {
  return x.toFixed(digits);
}
fixed.test.js 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { fixed } from "./fixed.js";

const cases = [
  ["pi-two", 3.14159, 2, "3.14"],
  ["pad-zeros", 1, 3, "1.000"],
  ["round-up", 1234.5678, 2, "1234.57"],
  ["zero-digits", 123.456, 0, "123"],
  ["float-error", 0.30000000000000004, 2, "0.30"],
  ["negative", -1.234, 1, "-1.2"],
  ["rounds-to-zero", 0.0049, 2, "0.00"],
  ["stored-below-2-675", 2.675, 2, "2.67"],
  ["stored-below-1-005", 1.005, 2, "1.00"],
  ["large", 1e+20, 2, "100000000000000000000.00"],
  ["many-digits", 0.1, 20, "0.10000000000000000555"],
  ["integer-value", 42, 2, "42.00"],
];

for (const [name, x, digits, want] of cases) {
  test(name, () => {
    assert.equal(fixed(x, digits), want);
  });
}
fixed.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

/**
 * Returns x with exactly digits digits after the decimal point. toFixed
 * rounds the exact binary value of x. It uses an exponent for 1e21 and more.
 */
export function fixed(x: number, digits: number): string {
  return x.toFixed(digits);
}
fixed.test.ts 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { fixed } from "./fixed.ts";

const cases: [string, number, number, string][] = [
  ["pi-two", 3.14159, 2, "3.14"],
  ["pad-zeros", 1, 3, "1.000"],
  ["round-up", 1234.5678, 2, "1234.57"],
  ["zero-digits", 123.456, 0, "123"],
  ["float-error", 0.30000000000000004, 2, "0.30"],
  ["negative", -1.234, 1, "-1.2"],
  ["rounds-to-zero", 0.0049, 2, "0.00"],
  ["stored-below-2-675", 2.675, 2, "2.67"],
  ["stored-below-1-005", 1.005, 2, "1.00"],
  ["large", 1e+20, 2, "100000000000000000000.00"],
  ["many-digits", 0.1, 20, "0.10000000000000000555"],
  ["integer-value", 42, 2, "42.00"],
];

for (const [name, x, digits, want] of cases) {
  test(name, () => {
    assert.equal(fixed(x, digits), want);
  });
}
fixed.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

// Package fixed writes a number with a fixed count of decimals.
package fixed

import "strconv"

// Fixed returns x with exactly digits digits after the decimal point. It
// rounds the exact binary value of x.
func Fixed(x float64, digits int) string {
	return strconv.FormatFloat(x, 'f', digits, 64)
}
fixed_test.go 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

package fixed

import "testing"

var cases = []struct {
	name   string
	x      float64
	digits int
	want   string
}{
	{"pi-two", 3.14159, 2, "3.14"},
	{"pad-zeros", 1.0, 3, "1.000"},
	{"round-up", 1234.5678, 2, "1234.57"},
	{"zero-digits", 123.456, 0, "123"},
	{"float-error", 0.30000000000000004, 2, "0.30"},
	{"negative", -1.234, 1, "-1.2"},
	{"rounds-to-zero", 0.0049, 2, "0.00"},
	{"stored-below-2-675", 2.675, 2, "2.67"},
	{"stored-below-1-005", 1.005, 2, "1.00"},
	{"large", 1e+20, 2, "100000000000000000000.00"},
	{"many-digits", 0.1, 20, "0.10000000000000000555"},
	{"integer-value", 42.0, 2, "42.00"},
}

func TestFixed(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := Fixed(c.x, c.digits); got != c.want {
				t.Fatalf("Fixed(%v, %d) = %q, want %q", c.x, c.digits, got, c.want)
			}
		})
	}
}
fixed.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

/// Returns x with exactly digits digits after the decimal point. It rounds
/// the exact binary value of x.
pub fn fixed(x: f64, digits: usize) -> String {
    format!("{x:.digits$}")
}
tests/fixed_test.rs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

use algo_format_a_number_with_fixed_decimals::fixed;

const CASES: &[(&str, f64, usize, &str)] = &[
    ("pi-two", 3.14159, 2, "3.14"),
    ("pad-zeros", 1.0, 3, "1.000"),
    ("round-up", 1234.5678, 2, "1234.57"),
    ("zero-digits", 123.456, 0, "123"),
    ("float-error", 0.30000000000000004, 2, "0.30"),
    ("negative", -1.234, 1, "-1.2"),
    ("rounds-to-zero", 0.0049, 2, "0.00"),
    ("stored-below-2-675", 2.675, 2, "2.67"),
    ("stored-below-1-005", 1.005, 2, "1.00"),
    ("large", 1e+20, 2, "100000000000000000000.00"),
    ("many-digits", 0.1, 20, "0.10000000000000000555"),
    ("integer-value", 42.0, 2, "42.00"),
];

#[test]
fn cases() {
    for &(name, x, digits, want) in CASES {
        assert_eq!(fixed(x, digits), want, "{name}");
    }
}
fixed.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

# fixed x digits: print x with exactly digits digits after the decimal point.
# The shell printf reads x as a long double, so the extra digits are not
# those of a double. awk uses a double, and LC_ALL=C gives a dot.
fixed() {
  LC_ALL=C awk -v x="$1" -v d="$2" 'BEGIN { printf("%." d "f\n", x) }'
}
test_fixed.bats 67 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/format-a-number-with-fixed-decimals/.

setup() {
  source "$BATS_TEST_DIRNAME/fixed.sh"
}

@test "pi-two" {
  run fixed 3.14159 2
  [ "$output" = '3.14' ]
}

@test "pad-zeros" {
  run fixed 1 3
  [ "$output" = '1.000' ]
}

@test "round-up" {
  run fixed 1234.5678 2
  [ "$output" = '1234.57' ]
}

@test "zero-digits" {
  run fixed 123.456 0
  [ "$output" = '123' ]
}

@test "float-error" {
  run fixed 0.30000000000000004 2
  [ "$output" = '0.30' ]
}

@test "negative" {
  run fixed -1.234 1
  [ "$output" = '-1.2' ]
}

@test "rounds-to-zero" {
  run fixed 0.0049 2
  [ "$output" = '0.00' ]
}

@test "stored-below-2-675" {
  run fixed 2.675 2
  [ "$output" = '2.67' ]
}

@test "stored-below-1-005" {
  run fixed 1.005 2
  [ "$output" = '1.00' ]
}

@test "large" {
  run fixed 1e+20 2
  [ "$output" = '100000000000000000000.00' ]
}

@test "many-digits" {
  run fixed 0.1 20
  [ "$output" = '0.10000000000000000555' ]
}

@test "integer-value" {
  run fixed 42 2
  [ "$output" = '42.00' ]
}

References

  1. Rosetta Code, Formatted numeric output (task text, from acmeism/RosettaCodeData), task text
  2. Floating-Point Arithmetic, Issues and Limitations, The Python Tutorial, 15.1 Representation Error
  3. string, Common string operations, Python documentation, Format Specification Mini-Language
  4. Number.prototype.toFixed(), MDN Web Docs, Description; Examples
  5. Class Formatter, Java SE 25 API, Float and Double
  6. Class BigDecimal, Java SE 25 API, BigDecimal(double val)
  7. Standard numeric format strings, .NET documentation, Precision specifier; Fixed-point format specifier (F)
  8. Package fmt, The Go Standard Library, Printing; Width and precision
  9. Module std::fmt, The Rust Standard Library, Precision
  10. printf, fprintf, sprintf, snprintf, C reference, cppreference.com, Parameters; conversion specification
  11. Standard format specification, C++ reference, cppreference.com, Type

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source