How do I add leading zeros to a number?
Category: java.lang, viewed: 1554 time(s).
This example shows you how to use the String.format() method to add zero padding to a number. If you just want to print out the result you can use System.out.format(). This method is available since Java 1.5, so If you use a previous version you can use the NumberFormat class (e175. How do I format a number with leading zeros?).
package org.kodejava.example.lang; public class LeadingZerosExample { public static void main(String[] args) { int number = 1500; // // String format below will add leading zeros (the %0 syntax) to the number above. // The length of the formatted string will be 7 characters. // String formatted = String.format("%07d", number); System.out.println("Number with leading zeros: " + formatted); } } |
For more information about the format syntax you can find it here.
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I read system property as an integer?
- How do I decode string to integer?
- How do I insert a string in the StringBuilder?
- How do I remove substring from StringBuilder?
- How do I reverse a string by word?
- How do I convert varargs to an array?
- How do I remove trailing white space from a string?
- How do I remove leading white space from a string?
- How do I create a method that accept varargs in Java?
- How do I know a class of an object?