Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 \nd2 = %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("\nd1 = %5.3f \nd2 = %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 \nd2 = %8g", d1, d2);
System.out.printf("\nd1 = %5.3f \nd2 = %2.5f", d1, d2);
}
}
Output
d1 = 399.89 d2 = 298.877 d1 = 399.888 d2 = 298.87690
Advertisements
