Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string, integer with leading zeros

I want to convert an integer value to a string with leading zeroes (if necessary) such that the string has 3 total characters. For example, 5 would become "005", and 10 would become "010".

I've tried this code:

NSString* strName = [NSString stringWithFormat:@"img_00%d.jpg", i]; 

This partially works, but if i has the value of 10, for example, the result is img_0010.jpg, not img_010.jpg.

Is there a way to do what I want?

like image 391
ghiboz Avatar asked Jun 06 '10 17:06

ghiboz


People also ask

Can an integer have leading zeros?

You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string. This article shows how to use both methods to pad a number with leading zeros.

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 can I pad an integer with zeros on the left?

format("%05d", yournumber); for zero-padding with a length of 5.


1 Answers

Use the format string "img_%03d.jpg" to get decimal numbers with three digits and leading zeros.

like image 93
Gumbo Avatar answered Oct 14 '22 22:10

Gumbo