Logo

Programming-Idioms

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

Idiom #173 Format a number with grouped thousands

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

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'
#define _POSIX_C_SOURCE 200809L
#include <locale.h>
#include <stdio.h>
setlocale(LC_ALL, "");
printf("%'d\n", 1000);

New implementation...
cup