Logo

Programming-Idioms

  • Rust
  • Perl

Idiom #173 Format a number with grouped thousands

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

 sub commify {
    local $_  = shift;
    1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
    return $_;
}

Loop over a string and insert a string every three characters, until you can't.
use separator::Separatable;
println!("{}", 1000.separated_string());

Requires the separator crate
#define _POSIX_C_SOURCE 200809L
#include <locale.h>
#include <stdio.h>
setlocale(LC_ALL, "");
printf("%'d\n", 1000);

New implementation...
cup