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.

#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;
DecimalFormat decimalFormat = new DecimalFormat("#,###");
String formattedString = decimalFormat.format(1000000);
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:,}'
require 'active_support/all'
1000.to_s(:delimited)
'1000'.reverse.scan(/.{1,3}/).join(',').reverse
'1000'.gsub(/\B(?=(...)*\b)/, ',')
use separator::Separatable;
println!("{}", 1000.separated_string());
"%,d".format(n)

New implementation...
< >
cup