- Trending Categories
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
Set width and precision to format output in Java
Set width in output as shown below. Here, %10 sets a 10 character field
System.out.printf("d1 = %10.2f
d2 = %8g", d1, d2);
Above, the value after the decimal is for decimal places i.e. 5.3 is for 3 decimal places −
System.out.printf("
d1 = %5.3f
d2 = %2.5f", d1, d2);
The following is an example −
Example
public class Demo { public static void main(String[] args) throws Exception { double d1 = 399.8877; double d2 = 298.87690; System.out.printf("d1 = %10.2f
d2 = %8g", d1, d2); System.out.printf("
d1 = %5.3f
d2 = %2.5f", d1, d2); } }
Output
d1 = 399.89 d2 = 298.877 d1 = 399.888 d2 = 298.87690
- Related Articles
- Precision on a number format in Java
- Format Output with Formatter in Java
- Precision String Format Specifier In Swift
- How to set Line Border color and width with Java?
- Set a Minimum Field Width in Java
- Precision Handling in Java
- How to get process output in GridView format in PowerShell ?
- How to set viewport height and width in CSS
- How to set cell width and height in HTML?
- How to convert command output to the Hashtable format in PowerShell?
- Java Program to get Temporal Queries precision
- How to format a floating number to fixed width in Python?
- Parse and format to hexadecimal in Java
- How to set table width in HTML?
- Set min-width and max-width of an element using CSS

Advertisements