[Haskell-cafe] Number formatting

Stephen Tetley stephen.tetley at gmail.com
Mon Feb 8 08:09:23 EST 2010


Hello All

Alternatively, less dependencies and a bit less golf (but not much testing...):


Best wishes

Stephen


import Data.List
import Numeric



formatDecimal :: RealFloat a => a -> String
formatDecimal d = let s     = showFFloat (Just 2) d ""
                      (a,b) = break (=='.') s
                  in (intersperseN 3 ',' a) ++ b


intersperseN :: Int -> a -> [a] -> [a]
intersperseN n a = snd . para phi (1,[]) where
  phi x ((_:_), (i,acc)) | i == n = (1,   a : x : acc)
  phi x (_,     (i,acc))          = (i+1, x : acc)

-- paramorphism (generalizes fold)
para :: (a -> ([a], b) -> b) -> b -> [a] -> b
para phi b = step
  where step []     = b
        step (x:xs) = phi x (xs, step xs)



On 8 February 2010 11:17, Anton van Straaten <anton at appsolutions.com> wrote:

> There's a small function to do it here:
>
> http://bluebones.net/2007/02/formatting-decimals-in-haskell/


More information about the Haskell-Cafe mailing list