Search code examples
purescript

Does PureScript support “format strings” like C / Java etc.?


I need to output a number with leading zeros and as six digits. In C or Java I would use "%06d" as a format string to do this. Does PureScript support format strings? Or how would I achieve this?


Solution

  • I don't know of any module that would support a printf-style functionality in PureScript. It would be very nice to have a type-safe way to format numbers.

    In the meantime, I would write something likes this:

    import Data.String (length, fromCharArray)
    import Data.Array (replicate)
    
    -- | Pad a string with the given character up to a maximum length.
    padLeft :: Char -> Int -> String -> String
    padLeft c len str = prefix <> str
      where prefix = fromCharArray (replicate (len - length str) c)
    
    -- | Pad a number with leading zeros up to the given length.
    padZeros :: Int -> Int -> String
    padZeros len num | num >= 0  = padLeft '0' len (show num)
                     | otherwise = "-" <> padLeft '0' len (show (-num))
    

    Which produces the following results:

    > padZeros 6 8
    "000008"
    
    > padZeros 6 678
    "000678"
    
    > padZeros 6 345678
    "345678"
    
    > padZeros 6 12345678
    "12345678"
    
    > padZeros 6 (-678)
    "-000678"
    

    Edit: In the meantime, I've written a small module that can format numbers in this way: https://github.com/sharkdp/purescript-format

    For your particular example, you would need to do the following:

    If you want to format Integers:

    > format (width 6 <> zeroFill) 123
    "000123"
    

    If you want to format Numbers

    > format (width 6 <> zeroFill <> precision 1) 12.345
    "0012.3"