6

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?

0dB
  • 675
  • 5
  • 13

1 Answers1

2

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"
shark.dp
  • 365
  • 3
  • 11
  • 1
    I've actually started working on a library to support this: https://github.com/sharkdp/purescript-format – shark.dp Mar 06 '16 at 15:52
  • Cool, I’ll have a closer look what you are doing there with Monoid and Semigroup. BTW, your solution above is more general than the one I have written myself yesterday I’m still trying to get the hang of PureScript (strict, no (:) for Array de-structuring in recursion, data type `Tuple` instead of `(,)`, and a few more things). – 0dB Mar 06 '16 at 16:05
  • I have released a first version of purescript-format. I've updated my answer accordingly. The Semigroup/Monoid instance for the Properties is only used to combine them in an easy way. – shark.dp Mar 06 '16 at 20:41
  • Yes, I saw that, by defining `append` and providing an ‘empty’ default. Sieht gut aus – 0dB Mar 06 '16 at 20:53