Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double decimal formatting in Java

People also ask

How do you do 2 decimal places in Java?

printf("%. 2f", value); The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (.

Can I format a double in Java?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.

Can double have decimal in Java?

The number of decimal places in a double is 16.

What is 2f in Java?

In short, the %. 2f syntax tells Java to return your variable ( val ) with 2 decimal places ( . 2 ) in decimal representation of a floating-point number ( f ) from the start of the format specifier ( % ). There are other conversion characters you can use besides f : d : decimal integer.


One of the way would be using NumberFormat.

NumberFormat formatter = new DecimalFormat("#0.00");     
System.out.println(formatter.format(4.0));

Output:

4.00


With Java 8, you can use format method..: -

System.out.format("%.2f", 4.0); // OR

System.out.printf("%.2f", 4.0); 
  • f is used for floating point value..
  • 2 after decimal denotes, number of decimal places after .

For most Java versions, you can use DecimalFormat: -

    DecimalFormat formatter = new DecimalFormat("#0.00");
    double d = 4.0;
    System.out.println(formatter.format(d));

Use String.format:

String.format("%.2f", 4.52135);

As per docs:

The locale always used is the one returned by Locale.getDefault().


Using String.format, you can do this:

double price = 52000;
String.format("$%,.2f", price);

Notice the comma which makes this different from @Vincent's answer

Output:

$52,000.00

A good resource for formatting is the official java page on the subject


You could always use the static method printf from System.out - you'd then implement the corresponding formatter; this saves heap space in which other examples required you to do.

Ex:

System.out.format("%.4f %n", 4.0); 

System.out.printf("%.2f %n", 4.0); 

Saves heap space which is a pretty big bonus, nonetheless I hold the opinion that this example is much more manageable than any other answer, especially since most programmers know the printf function from C (Java changes the function/method slightly though).


double d = 4.0;
DecimalFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
System.out.println(nf.format("#.##"));