- 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
Format numerical data with printf in Java
First, we have taken a double variable and displayed it twice.
double d = 399.8877; System.out.printf("d1 = %2$f d2 = %1$g", d, d);
After that, we have formatted numerical int data −
int val1 = 90, val2 = 35, val3 = 88, val4 = 600; System.out.printf("
val1 = %d, val2 = %x, val3 = %o, val4 = %d", val1, val2, val3, val4); System.out.printf("
val2 = %4$d, val2 = %3$d, val3 = %2$o, val4 = %1$d", val1, val2, val3, val4);
Above, we have displayed %o for octal, %x for hexadecimal, %d for integer, etc.
The following is the complete example −
Example
public class Demo { public static void main(String[] args) throws Exception { int val1 = 90, val2 = 35, val3 = 88, val4 = 600; double d = 399.8877; System.out.printf("d1 = %2$f d2 = %1$g", d, d); System.out.printf("
val1 = %d, val2 = %x, val3 = %o, val4 = %d", val1, val2, val3, val4); System.out.printf("
val2 = %4$d, val2 = %3$d, val3 = %2$o, val4 = %1$d", val1, val2, val3, val4); } }
Output
d1 = 399.887700 d2 = 399.888 val1 = 90, val2 = 23, val3 = 130, val4 = 600 val2 = 600, val2 = 88, val3 = 43, val4 = 90
Advertisements