- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to add leading zeros to a number
To add leading zeros to a number, you need to format the output. Let’s say we need to add 4 leading zeros to the following number with 3 digits.
int val = 290;
For adding 4 leading zeros above, we will use %07d i.e. 4+3 = 7. Here, 3, as shown above, is the number with 3 digits.
String.format("%07d", val);
The following is the final example.
Example
import java.util.Formatter; public class Demo { public static void main(String args[]) { int val = 290; System.out.println("Integer: "+val); String formattedStr = String.format("%07d", val); System.out.println("With leading zeros = " + formattedStr); } }
Output
Integer: 290 With leading zeros = 0000290
Advertisements