Close

Java String Formatting - How to format floating point using String#printf()?

Java String Formatting Java 

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

The format specifiers %f is used for this purpose.

The result is formatted as a decimal number.

Types include: float, Float, double, Double, and BigDecimal

package com.logicbig.example.string;

import java.math.BigDecimal;

public class StringPrintfFloatingPoint {

public static void main(String[] args) {
System.out.printf("%f%n", 1.77f);
System.out.printf("%f%n", 1.77d);
System.out.printf("%f%n", Double.valueOf(1.77d));
System.out.printf("%f%n", BigDecimal.valueOf(1.77d));
//including # flag in decimal number even if the fractional portion is zero
System.out.printf("[%#1.0f]%n", 67899d);
System.out.printf("[%#1.2f]%n", 67899d);
System.out.printf("[%1.0f]%n", 67899d);
}
}

Output

1.770000
1.770000
1.770000
1.770000
[67899.]
[67899.00]
[67899]




See Also