Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pad an integer with zeros on the left?

How do you left pad an int with zeros when converting to a String in java?

I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).

like image 596
Omar Kooheji Avatar asked Jan 23 '09 15:01

Omar Kooheji


People also ask

How can I pad a string with zeros on the left?

leftPad() method to left pad a string with zeros, by adding leading zeros to string.

How do you pad a number with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

How do you pad an integer with zeros on the left in Python?

To pad zeros to a string, use the str. zfill() method. It takes one argument: the final length of the string you want and pads the string with zeros to the left.

What is a zero padded number?

Zero padding is a technique typically employed to make the size of the input sequence equal to a power of two. In zero padding, you add zeros to the end of the input sequence so that the total number of samples is equal to the next higher power of two.


1 Answers

Use java.lang.String.format(String,Object...) like this:

String.format("%05d", yournumber); 

for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".

The full formatting options are documented as part of java.util.Formatter.

like image 53
Yoni Roit Avatar answered Sep 28 '22 05:09

Yoni Roit