Does PureScript support "string formatting," for example, C / Java, etc.?

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

+4
source share
1 answer

I do not know a single module that supports the printf style function in PureScript. It would be very nice to have a safe way to format numbers.

At the same time, I would write something like 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 gives the following results:

> padZeros 6 8
"000008"

> padZeros 6 678
"000678"

> padZeros 6 345678
"345678"

> padZeros 6 12345678
"12345678"

> padZeros 6 (-678)
"-000678"

:. , : https://github.com/sharkdp/purescript-format

:

:

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

Numbers

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

All Articles