Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add left-padded zeros to a number in Java? [duplicate]

I have an integer 100, how do I format it to look like 00000100 (always 8 digits long)?

like image 302
Stig Christian Avatar asked Apr 24 '10 15:04

Stig Christian


People also ask

How do you add leading zeros to a number in Java?

You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.

How do you add a trailing space in Java?

One way to do this is with string format codes. For example, if you want to pad a string to a certain length with spaces, use something like this: String padded = String. format("%-20s", str);

How do you make a string of zeros in Java?

There are two main ways to add zeros at the start of an integer number in Java, first by using format() method of String class, and second by using format() method of DecimalFormat class. String.


1 Answers

Try this:

String formattedNumber = String.format("%08d", number);
like image 55
Andrew Hare Avatar answered Sep 20 '22 15:09

Andrew Hare