Programming Search⌘K

Taskintro

Format a number with separators

Also called thousands separator, digit grouping, group separator, comma separator, commatize, format with commas, number with commas, %'d, {:,}, toLocaleString, N0 format, grouping separator.

Write an integer with a comma between each group of 3 digits, as in 1,234,567, with a format option, a locale API or a short loop. The result must not change with the locale of the computer.

Task

Write an integer in decimal with a separator between each group of 3 digits, so that a person can read a large number quickly. The Rosetta Code task Commatizing numbers describes a function that "adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string"1. This task does the main part of that work for one integer.

The function group_thousands(n) returns the digits of n with a comma before each group of 3 digits, counted from the right. A negative number has a minus sign first.

n Result
1234567 1,234,567
1000 1,000
42 42
-1234567 -1,234,567

The separator is not the same in all countries. Wikipedia lists "Three ways to group the number ten thousand with digit group separators"2: a space, a full stop and a comma. The size of the groups also changes: India puts the first separator after 3 digits and the next ones after each 2 digits. This task uses one fixed format, a comma and groups of 3, so the result is the same on each computer. For a format that follows the user's locale, see Locale-aware formatting.

Solutions

Language Fixed format, comma and groups of 3 Locale format
Python f"{n:,}" locale.format_string("%d", n, grouping=True)
JavaScript, TypeScript a loop or a regular expression n.toLocaleString("en-US")
Java String.format(Locale.ROOT, "%,d", n) String.format("%,d", n)
C# n.ToString("N0", CultureInfo.InvariantCulture) n.ToString("N0")
Go a loop over the digits golang.org/x/text/message, outside the standard library
Rust a loop over the digits a crate, outside the standard library
C a loop over the digits printf("%'lld", n) after setlocale
C++ a loop over the digits std::format(loc, "{:L}", n)
Bash a loop with a regular expression printf "%'d" in a locale with grouping
  • Python. The format option , "Inserts a comma every 3 digits for integer presentation type 'd' and floating-point presentation types, excluding 'n'"3. The option _ puts an underscore. The type n uses the separator of the locale.
  • JavaScript. toLocaleString and Intl.NumberFormat use the rules of a locale. The locale en-US gives commas and groups of 3. MDN shows that "India uses thousands/lakh/crore separators"4, with the result 1,23,456.789. Both work with BigInt, so a 64-bit value keeps all its digits.
  • TypeScript. The same as JavaScript. The type of the parameter is number | bigint.
  • Java. With the flag ,, "The result will include locale-specific grouping separators"5. Locale.ROOT gives a comma and groups of 3. Without a locale, the default locale of the computer is used, so the result can change.
  • C#. The format N gives "Integral and decimal digits, group separators, and a decimal separator with optional negative sign"6, and N0 gives no decimals. The culture gives the separator: NumberGroupSeparator "Defines the string that separates groups of integral numbers"6. The invariant culture gives a comma.
  • Go. The package fmt has no grouping. The solution writes the digits with strconv.FormatInt and adds a comma before each group of 3.
  • Rust. The standard library has no grouping and no locale. Its format functions "do not have any concept of locale and will produce the same results on all systems regardless of user configuration"7. The solution uses a loop.
  • C. POSIX adds the flag ' (an apostrophe) to printf: "The integer portion of the result of a decimal conversion (%i, %d, %u, %f, %F, %g, or %G) shall be formatted with thousands' grouping characters"8. The character comes from the locale, and the default C locale has no separator. Standard C has no grouping, so the portable solution uses a loop.
  • C++. std::format has the option L: "For integral types, the locale-specific form inserts the appropriate digit group separator characters"9. The locale must be given or set, so the solution uses a loop.
  • Bash. printf "%'d" uses the locale of the shell. The solution uses a loop that adds one comma at a time with [[ =~ ]].

The Python solution, with the other options of the format:

n = 1234567
print(f"{n:,}")
print(f"{n:_}")
print(f"{-9223372036854775808:,}")
print(f"{1234567.891:,.2f}")
Output
1,234,567
1_234_567
-9,223,372,036,854,775,808
1,234,567.89

The loop is the same in all languages. Write the digits of the absolute value, then copy them and put a comma before each digit whose distance from the end is a multiple of 3. The Go solution:

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func groupThousands(n int64) string {
	s := strconv.FormatInt(n, 10)
	sign := ""
	if s[0] == '-' {
		sign, s = "-", s[1:]
	}
	var b strings.Builder
	b.WriteString(sign)
	for i, c := range s {
		if i > 0 && (len(s)-i)%3 == 0 {
			b.WriteByte(',')
		}
		b.WriteRune(c)
	}
	return b.String()
}

func main() {
	for _, n := range []int64{0, 999, 1000, -1234567, -9223372036854775808} {
		fmt.Println(groupThousands(n))
	}
}
Output
0
999
1,000
-1,234,567
-9,223,372,036,854,775,808

Edge cases

  • Zero and numbers under 1000. No separator: 0, 42 and 999.
  • The boundary of a group. 100000 is 100,000 and 1000000 is 1,000,000. A loop that counts from the left gives 1,000,00 or puts a comma first.
  • Negative numbers. The minus sign is not a digit. -999 is -999, not -,999.
  • The smallest 64-bit value. -9223372036854775808 has no positive value in 64 bits, so abs(n) or -n overflows. Convert the number to text first, and then take off the sign, as the Go solution does.
  • Numbers with a fraction. Group only the digits before the decimal point. The digits after the point are not grouped in most styles.

Pitfalls

  • A regular expression that also groups the fraction. A common one line solution puts a comma at each position that has a multiple of 3 digits after it. It is correct for an integer, but it also changes the digits after the decimal point:

This code runs but gives a wrong answer on purpose.

const group = (s) => s.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(group("1234567"));
console.log(group("1234.5678"));
Output
1,234,567
1,234.5,678

Split the text at the decimal point and group only the integer part, or use Intl.NumberFormat.

  • The locale of the computer. Java String.format("%,d", n), C# n.ToString("N0"), C %'d and Bash %'d all use the locale of the computer. The same program gives 1,234,567 in the United States and 1.234.567 in Germany. Data for a file or for another program must use a fixed format. Give the locale explicitly: Locale.ROOT, CultureInfo.InvariantCulture or en-US.
  • Separators in data. A number with separators is text for people. Most parsers do not read it back: int("1,234") fails in Python, and parseInt("1,234") in JavaScript stops at the comma and gives 1.
  • The size of the groups. Not all locales use groups of 3. A loop with a fixed group size is correct only for the format that the program chose.

Code

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

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


def group_thousands(n: int) -> str:
    """Return n in decimal with a comma between each group of 3 digits."""
    return f"{n:,}"


if __name__ == "__main__":
    print(group_thousands(1234567))
    print(group_thousands(-1000))
test_group.py 26 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/format-a-number-with-separators/.

import pytest

from group import group_thousands

CASES = [
    ("million", 1234567, "1,234,567"),
    ("thousand", 1000, "1,000"),
    ("small", 42, "42"),
    ("zero", 0, "0"),
    ("three-digits", 999, "999"),
    ("negative", -1234567, "-1,234,567"),
    ("negative-small", -999, "-999"),
    ("negative-thousand", -1000, "-1,000"),
    ("int64-max", 9223372036854775807, "9,223,372,036,854,775,807"),
    ("int64-min", -9223372036854775808, "-9,223,372,036,854,775,808"),
    ("six-digits", 100000, "100,000"),
    ("seven-digits", 1000000, "1,000,000"),
]


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

#ifndef GROUP_HPP
#define GROUP_HPP

#include <cstddef>
#include <cstdint>
#include <string>

// Returns n in decimal with a comma between each group of 3 digits. It
// converts n to text first, so the smallest int64_t does not overflow.
inline std::string group_thousands(std::int64_t n) {
    const std::string s = std::to_string(n);
    const std::size_t start = s[0] == '-' ? 1 : 0;
    const std::size_t len = s.size() - start;
    std::string out = s.substr(0, start);
    for (std::size_t i = 0; i < len; ++i) {
        if (i > 0 && (len - i) % 3 == 0) {
            out += ',';
        }
        out += s[start + i];
    }
    return out;
}

#endif
test_group.cpp 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

#include <climits>
#include <cstdint>
#include <cstdio>

#include "group.hpp"

namespace {

struct test_case {
    const char* name;
    std::int64_t n;
    const char* want;
};

const test_case cases[] = {
    {"million", 1234567, "1,234,567"},
    {"thousand", 1000, "1,000"},
    {"small", 42, "42"},
    {"zero", 0, "0"},
    {"three-digits", 999, "999"},
    {"negative", -1234567, "-1,234,567"},
    {"negative-small", -999, "-999"},
    {"negative-thousand", -1000, "-1,000"},
    {"int64-max", 9223372036854775807LL, "9,223,372,036,854,775,807"},
    {"int64-min", LLONG_MIN, "-9,223,372,036,854,775,808"},
    {"six-digits", 100000, "100,000"},
    {"seven-digits", 1000000, "1,000,000"},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const std::string got = group_thousands(c.n);
        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;
}
Group.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

import java.util.Locale;

/** An integer with a separator between each group of 3 digits. */
public final class Group {
    private Group() {}

    /**
     * Returns n in decimal with a comma between each group of 3 digits.
     * Locale.ROOT gives the comma on each computer.
     */
    public static String groupThousands(long n) {
        return String.format(Locale.ROOT, "%,d", n);
    }

    public static void main(String[] args) {
        System.out.println(groupThousands(1234567));
    }
}
GroupTest.java 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

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 GroupTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("million", (long) 1234567, "1,234,567"),
                Arguments.of("thousand", (long) 1000, "1,000"),
                Arguments.of("small", (long) 42, "42"),
                Arguments.of("zero", (long) 0, "0"),
                Arguments.of("three-digits", (long) 999, "999"),
                Arguments.of("negative", (long) -1234567, "-1,234,567"),
                Arguments.of("negative-small", (long) -999, "-999"),
                Arguments.of("negative-thousand", (long) -1000, "-1,000"),
                Arguments.of("int64-max", 9223372036854775807L, "9,223,372,036,854,775,807"),
                Arguments.of("int64-min", Long.MIN_VALUE, "-9,223,372,036,854,775,808"),
                Arguments.of("six-digits", (long) 100000, "100,000"),
                Arguments.of("seven-digits", (long) 1000000, "1,000,000")
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void groupThousands(String name, long n, String want) {
        assertEquals(want, Group.groupThousands(n));
    }
}
group.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

#include "group.h"

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

void group_thousands(char *out, long long n) {
    char digits[24];
    snprintf(digits, sizeof digits, "%lld", n);
    const char *d = digits;
    if (*d == '-') {
        *out++ = *d++;
    }
    size_t len = strlen(d);
    for (size_t i = 0; i < len; i++) {
        if (i > 0 && (len - i) % 3 == 0) {
            *out++ = ',';
        }
        *out++ = d[i];
    }
    *out = '\0';
}
group.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

#ifndef GROUP_H
#define GROUP_H

// The size of a buffer that holds each result, with the null byte.
#define GROUP_THOUSANDS_SIZE 27

// Writes n in decimal with a comma between each group of 3 digits into out,
// which must hold GROUP_THOUSANDS_SIZE bytes.
void group_thousands(char *out, long long n);

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

#include "group.h"

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

struct test_case {
    const char *name;
    long long n;
    const char *want;
};

static const struct test_case cases[] = {
    {"million", 1234567, "1,234,567"},
    {"thousand", 1000, "1,000"},
    {"small", 42, "42"},
    {"zero", 0, "0"},
    {"three-digits", 999, "999"},
    {"negative", -1234567, "-1,234,567"},
    {"negative-small", -999, "-999"},
    {"negative-thousand", -1000, "-1,000"},
    {"int64-max", 9223372036854775807LL, "9,223,372,036,854,775,807"},
    {"int64-min", LLONG_MIN, "-9,223,372,036,854,775,808"},
    {"six-digits", 100000, "100,000"},
    {"seven-digits", 1000000, "1,000,000"},
};

int main(void) {
    int failures = 0;
    char buf[GROUP_THOUSANDS_SIZE];
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        group_thousands(buf, c->n);
        if (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;
}
Group.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

using System.Globalization;

/// <summary>An integer with a separator between each group of 3 digits.</summary>
public static class Group
{
    /// <summary>
    /// Returns n in decimal with a comma between each group of 3 digits. The
    /// invariant culture gives the comma on each computer.
    /// </summary>
    public static string GroupThousands(long n) =>
        n.ToString("N0", CultureInfo.InvariantCulture);
}
GroupTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

using Xunit;

public sealed class GroupTests
{
    public static TheoryData<string, long, string> Cases => new()
    {
        { "million", 1234567, "1,234,567" },
        { "thousand", 1000, "1,000" },
        { "small", 42, "42" },
        { "zero", 0, "0" },
        { "three-digits", 999, "999" },
        { "negative", -1234567, "-1,234,567" },
        { "negative-small", -999, "-999" },
        { "negative-thousand", -1000, "-1,000" },
        { "int64-max", 9223372036854775807, "9,223,372,036,854,775,807" },
        { "int64-min", long.MinValue, "-9,223,372,036,854,775,808" },
        { "six-digits", 100000, "100,000" },
        { "seven-digits", 1000000, "1,000,000" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void GroupThousands(string name, long n, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Group.GroupThousands(n));
    }
}
group.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

/**
 * Returns n in decimal with a comma between each group of 3 digits. n can
 * be a number or a bigint, so a 64-bit value keeps all its digits.
 */
export function groupThousands(n) {
  const s = String(n);
  const sign = s.startsWith("-") ? "-" : "";
  const digits = s.slice(sign.length);
  let out = sign;
  for (let i = 0; i < digits.length; i++) {
    if (i > 0 && (digits.length - i) % 3 === 0) {
      out += ",";
    }
    out += digits[i];
  }
  return out;
}
group.test.js 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

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

import { groupThousands } from "./group.js";

const cases = [
  ["million", 1234567, "1,234,567"],
  ["thousand", 1000, "1,000"],
  ["small", 42, "42"],
  ["zero", 0, "0"],
  ["three-digits", 999, "999"],
  ["negative", -1234567, "-1,234,567"],
  ["negative-small", -999, "-999"],
  ["negative-thousand", -1000, "-1,000"],
  ["int64-max", 9223372036854775807n, "9,223,372,036,854,775,807"],
  ["int64-min", -9223372036854775808n, "-9,223,372,036,854,775,808"],
  ["six-digits", 100000, "100,000"],
  ["seven-digits", 1000000, "1,000,000"],
];

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

/**
 * Returns n in decimal with a comma between each group of 3 digits. n can
 * be a number or a bigint, so a 64-bit value keeps all its digits.
 */
export function groupThousands(n: number | bigint): string {
  const s = String(n);
  const sign = s.startsWith("-") ? "-" : "";
  const digits = s.slice(sign.length);
  let out = sign;
  for (let i = 0; i < digits.length; i++) {
    if (i > 0 && (digits.length - i) % 3 === 0) {
      out += ",";
    }
    out += digits[i];
  }
  return out;
}
group.test.ts 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

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

import { groupThousands } from "./group.ts";

const cases: [string, number | bigint, string][] = [
  ["million", 1234567, "1,234,567"],
  ["thousand", 1000, "1,000"],
  ["small", 42, "42"],
  ["zero", 0, "0"],
  ["three-digits", 999, "999"],
  ["negative", -1234567, "-1,234,567"],
  ["negative-small", -999, "-999"],
  ["negative-thousand", -1000, "-1,000"],
  ["int64-max", 9223372036854775807n, "9,223,372,036,854,775,807"],
  ["int64-min", -9223372036854775808n, "-9,223,372,036,854,775,808"],
  ["six-digits", 100000, "100,000"],
  ["seven-digits", 1000000, "1,000,000"],
];

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

// Package group writes an integer with a separator between each group of 3
// digits.
package group

import (
	"strconv"
	"strings"
)

// GroupThousands returns n in decimal with a comma between each group of 3
// digits. It converts n to text first, so the smallest int64 does not
// overflow.
func GroupThousands(n int64) string {
	s := strconv.FormatInt(n, 10)
	sign := ""
	if s[0] == '-' {
		sign, s = "-", s[1:]
	}
	var b strings.Builder
	b.WriteString(sign)
	for i := 0; i < len(s); i++ {
		if i > 0 && (len(s)-i)%3 == 0 {
			b.WriteByte(',')
		}
		b.WriteByte(s[i])
	}
	return b.String()
}
group_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

package group

import (
	"math"
	"testing"
)

var cases = []struct {
	name string
	n    int64
	want string
}{
	{"million", 1234567, "1,234,567"},
	{"thousand", 1000, "1,000"},
	{"small", 42, "42"},
	{"zero", 0, "0"},
	{"three-digits", 999, "999"},
	{"negative", -1234567, "-1,234,567"},
	{"negative-small", -999, "-999"},
	{"negative-thousand", -1000, "-1,000"},
	{"int64-max", 9223372036854775807, "9,223,372,036,854,775,807"},
	{"int64-min", math.MinInt64, "-9,223,372,036,854,775,808"},
	{"six-digits", 100000, "100,000"},
	{"seven-digits", 1000000, "1,000,000"},
}

func TestGroupThousands(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := GroupThousands(c.n); got != c.want {
				t.Fatalf("GroupThousands(%d) = %q, want %q", c.n, got, c.want)
			}
		})
	}
}
group.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

/// Returns n in decimal with a comma between each group of 3 digits. It
/// converts n to text first, so i64::MIN does not overflow.
pub fn group_thousands(n: i64) -> String {
    let s = n.to_string();
    let (sign, digits) = match s.strip_prefix('-') {
        Some(d) => ("-", d),
        None => ("", s.as_str()),
    };
    let mut out = String::from(sign);
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i) % 3 == 0 {
            out.push(',');
        }
        out.push(c);
    }
    out
}
tests/group_test.rs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-number-with-separators/.

use algo_format_a_number_with_separators::group_thousands;

const CASES: &[(&str, i64, &str)] = &[
    ("million", 1234567, "1,234,567"),
    ("thousand", 1000, "1,000"),
    ("small", 42, "42"),
    ("zero", 0, "0"),
    ("three-digits", 999, "999"),
    ("negative", -1234567, "-1,234,567"),
    ("negative-small", -999, "-999"),
    ("negative-thousand", -1000, "-1,000"),
    ("int64-max", 9223372036854775807, "9,223,372,036,854,775,807"),
    ("int64-min", i64::MIN, "-9,223,372,036,854,775,808"),
    ("six-digits", 100000, "100,000"),
    ("seven-digits", 1000000, "1,000,000"),
];

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

# group_thousands n: print n with a comma between each group of 3 digits.
# Each pass of the loop puts one comma before the last 3 digits that have
# no comma yet. The number stays text, so the shell does no arithmetic.
group_thousands() {
  local s=$1 sign=''
  if [[ $s == -* ]]; then
    sign=-
    s=${s#-}
  fi
  while [[ $s =~ ^([0-9]+)([0-9]{3})(,.*)?$ ]]; do
    s="${BASH_REMATCH[1]},${BASH_REMATCH[2]}${BASH_REMATCH[3]}"
  done
  printf '%s\n' "$sign$s"
}
test_group.bats 20 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/format-a-number-with-separators/.

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

@test "million" { run group_thousands 1234567; [ "$output" = '1,234,567' ]; }
@test "thousand" { run group_thousands 1000; [ "$output" = '1,000' ]; }
@test "small" { run group_thousands 42; [ "$output" = '42' ]; }
@test "zero" { run group_thousands 0; [ "$output" = '0' ]; }
@test "three-digits" { run group_thousands 999; [ "$output" = '999' ]; }
@test "negative" { run group_thousands -1234567; [ "$output" = '-1,234,567' ]; }
@test "negative-small" { run group_thousands -999; [ "$output" = '-999' ]; }
@test "negative-thousand" { run group_thousands -1000; [ "$output" = '-1,000' ]; }
@test "int64-max" { run group_thousands 9223372036854775807; [ "$output" = '9,223,372,036,854,775,807' ]; }
@test "int64-min" { run group_thousands -9223372036854775808; [ "$output" = '-9,223,372,036,854,775,808' ]; }
@test "six-digits" { run group_thousands 100000; [ "$output" = '100,000' ]; }
@test "seven-digits" { run group_thousands 1000000; [ "$output" = '1,000,000' ]; }

References

  1. Rosetta Code, Commatizing numbers (task text, from acmeism/RosettaCodeData), task text
  2. Decimal separator, Wikipedia, Introduction; Digit grouping
  3. string, Common string operations, Python documentation, Format Specification Mini-Language
  4. Intl.NumberFormat, MDN Web Docs, Examples
  5. Class Formatter, Java SE 25 API, Flags; Number Localization Algorithm
  6. Standard numeric format strings, .NET documentation, Number format specifier (N); NumberFormatInfo properties
  7. Module std::fmt, The Rust Standard Library, Localization
  8. fprintf, The Open Group Base Specifications Issue 8 (POSIX.1-2024), DESCRIPTION; flag characters
  9. Standard format specification, C++ reference, cppreference.com, L (locale-specific formatting)

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