- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- How to format date using printf() method in Java?
- How to format time using printf() method in Java?
- Display localized month name with printf method in Java
- How to use formatting with printf() correctly in Java?
- Format date with DateFormat.MEDIUM in Java
- Format date with DateFormat.LONG in Java
- Format Output with Formatter in Java
- Format Calendar with String.format() in Java
- Format date with DateFormat.SHORT in Java
- Format time with DateFormat.SHORT in Java
- Format time with DateFormat.FULL in Java
- Format Date with getDateTimeInstance() in Java
- Create a data frame with numerical as well as factor columns in R.
- Execution of printf with ++ operators in C
- Format currency with Java MessageFormat

Advertisements