Close

Java String Formatting - How to apply precision with floating point using String#printf()?

Java String Formatting Java 

This example shows how to use precision with floating-point with String#printf()

This is used for controlling the length of the decimal points.

Syntax: x.y; where x= padding (width) and y= decimal places.

If the precision is not specified then there is no explicit limit on the number of decimals.

package com.logicbig.example.string;

public class StringPrintfFloatPrecision {

public static void main(String[] args) {
System.out.printf("[%4.2f]%n", 98.76543);
System.out.printf("[%5.2f]%n", 98.76543);
System.out.printf("[%6.2f]%n", 98.76543);
System.out.printf("[%7.2f]%n", 98.76543);
System.out.printf("[%-7.2f]%n", 98.76543);
System.out.printf("[%7.4f]%n", 19.3);
System.out.printf("[%8.4f]%n", 19.3);
}
}

Output

[98.77]
[98.77]
[ 98.77]
[ 98.77]
[98.77 ]
[19.3000]
[ 19.3000]




See Also