Logo

Programming-Idioms

Number will be formatted with a comma separator between every group of thousands.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
#define _POSIX_C_SOURCE 200809L
#include <locale.h>
#include <stdio.h>
setlocale(LC_ALL, "");
printf("%'d\n", 1000);
$"{1000:n}"
import std.format;
string f = "%3,d".format(123456);
import "golang.org/x/text/language"
import "golang.org/x/text/message"
p := message.NewPrinter(language.English)
s := p.Sprintf("%d\n", 1000)
s :: Int -> String
s = intersperseN ',' 3 . show

intersperseN :: a -> Int -> [a] -> [a]
intersperseN x n = uncurry (<>) . foldr alg ([], [])
  where
    alg a (buf', acc)
      | length buf >= n = ([], (x:buf) <> acc)
      | otherwise = (buf, acc)
      where buf = a:buf'
new Intl.NumberFormat().format(1000);
import static java.text.NumberFormat.getNumberInstance;
import java.text.DecimalFormat;
DecimalFormat f = (DecimalFormat) getNumberInstance();
f.setGroupingSize(3);
s = f.format(1000);
import java.text.DecimalFormat;
DecimalFormat decimalFormat = new DecimalFormat("#,###");
String formattedString = decimalFormat.format(1000000);
String.format("%,d", 1000000);
import static java.lang.String.valueOf;
import static java.lang.System.out;
<N extends Number> String format(N n, char g, char d) {
    StringBuilder s = new StringBuilder();
    char a[] = valueOf(n).toCharArray();
    int i, m;
    for (i = 0, m = a.length; i < m; ++i)
        if (a[i] == d) {
            s.append(a, i, m - i);
            break;
        }
    while (i - 3 >= 0) {
        s.insert(0, a, i - 3, 3);
        if ((i = i - 3) > 0)
            s.insert(0, g);
    }
    s.insert(0, a, 0, i);
    return s.toString();
}
echo number_format(1000);
uses sysutils;
writeln(format('%.0n',[double(10000)]));   
 sub commify {
    local $_  = shift;
    1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
    return $_;
}
'{:,}'.format(1000)
f'{1000:,}'
format(1000, ',')
'1000'.reverse.scan(/.{1,3}/).join(',').reverse
require 'active_support/all'
1000.to_s(:delimited)
'1000'.gsub(/\B(?=(...)*\b)/, ',')
use separator::Separatable;
println!("{}", 1000.separated_string());
"%,d".format(n)