Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to string with leading zeros

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#

like image 658
Snæbjørn Avatar asked Nov 01 '16 14:11

Snæbjørn


People also ask

How do I print the leading zeros of a string?

Use the str. zfill() Function to Display a Number With Leading Zeros in Python. The str. zfill(width) function is utilized to return the numeric string; its zeros are automatically filled at the left side of the given width , which is the sole attribute that the function takes.

How do you add leading zeros to a string in Python?

For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.

How do I convert an int to a string in Python?

To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.


1 Answers

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"
like image 50
Chad Gilbert Avatar answered Oct 16 '22 08:10

Chad Gilbert