Convert haskell Int with leading zero to String

10,842

Solution 1

Depending on what you are planning to do you might want to store the "08" as a string and only convert to int when you need the value.

Solution 2

Use Text.Printf.printf:

printf "%02d" v

Make sure to import Text.Printf.printf first.

Solution 3

Its 8, not 08 in variable v. Yes, you assigned it 08 but it receives 8. Thats the reason show method displayed it as 8. You can use the work around given by Mipadi.

Edit:

Output of a test.

Prelude> Text.Printf.printf "%01d\n" 08
8
Prelude> Text.Printf.printf "%02d\n" 08
08
Prelude> Text.Printf.printf "%03d\n" 08
008

Output of another test.

Prelude> show 08
"8"
Prelude> show 008
"8"
Prelude> show 0008
"8"

I hope you get the point.

Edit:

Found another workaround. Try this,

"0" ++ show v

Solution 4

The printf way is probably best, but it's easy enough to write your own function:

show2d :: Int -> String 
show2d n | length (show n) == 1 = "0" ++ (show n)
         | otherwise = show n

Works as follows:

Prelude> show2d 1
"01"
Prelude> show2d 10
"10"
Prelude> show2d 100
"100"
Share:
10,842
rfgamaral
Author by

rfgamaral

Updated on July 26, 2022

Comments

  • rfgamaral
    rfgamaral almost 2 years

    Suppose I have a variable of type Int = 08, how can I convert this to String keeping the leading zero?

    For instance:

    v :: Int
    v = 08
    
    show v
    

    Output: 8

    I want the output to be "08".

    Is this possible?

  • Adeel Ansari
    Adeel Ansari about 15 years
    Doing opposite sounds better. Store it as int and change it to string for displaying purposes.
  • cevaris
    cevaris over 9 years
    it is just import Text.Printf
  • Chris Hanson
    Chris Hanson about 9 years
    Or import Text.Printf (printf)