12

I have an integer which I want to convert to a string with leading zeros.

So I have 1 and want to turn it into 01. 14 should turn into 14 not 014.

I tried:

let str = (string 1).PadLeft(2, '0') // visual studio suggested this one
let str = (string 1).PadLeft 2 '0'
let str = String.PadLeft 2 '0' (string 1)

But neither work :( When I search for something like this with F# I get stuff with printfn but I don't want to print to stdout :/

Disclaimer: This is my first F#

Snæbjørn
  • 10,322
  • 14
  • 65
  • 124

1 Answers1

23

You can use sprintf which returns a string rather than printing to stdout. Any of the print functions that start with an s return a string.

Use %0i to pad with zeroes. Add the length of the intended string between 0 and i. For example, to pad to four zeroes, you can use:

sprintf "%04i" 42

// returns "0042"
Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97