Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #173 Format a number with grouped thousands

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

require 'active_support/all'
1000.to_s(:delimited)
'1000'.reverse.scan(/.{1,3}/).join(',').reverse
'1000'.gsub(/\B(?=(...)*\b)/, ',')
#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);
String.format("%,d", 1000000);
import java.text.DecimalFormat;
import java.text.NumberFormat;
NumberFormat f = new DecimalFormat("#,###");
String s = f.format(1_234);
import static java.lang.System.out;
out.printf("%,f", 1_234.5);
import static java.lang.System.out;
import java.math.BigDecimal;
out.printf("%,f", new BigDecimal("1234.5"));
import static java.lang.System.out;
import java.math.BigInteger;
out.printf("%,d", new BigInteger("1234"));
import static java.text.NumberFormat.getNumberInstance;
import java.text.DecimalFormat;
DecimalFormat f = (DecimalFormat) getNumberInstance();
f.setGroupingSize(3);
String s = f.format(1_000);
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)
format(1000, ',')
f'{1000:,}'
use separator::Separatable;
println!("{}", 1000.separated_string());
"%,d".format(n)

New implementation...
cup