Double decimal formatting in Java

JavaFormattingDoubleDecimal

Java Problem Overview


I'm having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it's 4.00 instead?

Java Solutions


Solution 1 - Java

One of the way would be using NumberFormat.

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

Output:

4.00

Solution 2 - Java

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));

Solution 3 - Java

Use String.format:

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

As per docs:

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

Solution 4 - Java

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

Solution 5 - Java

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).

Solution 6 - Java

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

Solution 7 - Java

new DecimalFormat("#0.00").format(4.0d);

Solution 8 - Java

An alternative method is use the setMinimumFractionDigits method from the NumberFormat class.

Here you basically specify how many numbers you want to appear after the decimal point.

So an input of 4.0 would produce 4.00, assuming your specified amount was 2.

But, if your Double input contains more than the amount specified, it will take the minimum amount specified, then add one more digit rounded up/down

For example, 4.15465454 with a minimum amount of 2 specified will produce 4.155

NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
Double myVal = 4.15465454;
System.out.println(nf.format(myVal));

Try it online

Solution 9 - Java

There are many way you can do this. Those are given bellow:

Suppose your original number is given bellow:

 double number = 2354548.235;

Using NumberFormat:

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

    

Using String.format:

System.out.println(String.format("%,.2f", number));

Using DecimalFormat and pattern:

NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
        DecimalFormat decimalFormatter = (DecimalFormat) nf;
        decimalFormatter.applyPattern("#,###,###.##");
        String fString = decimalFormatter.format(number);
        System.out.println(fString);

    

Using DecimalFormat and pattern

DecimalFormat decimalFormat = new DecimalFormat("############.##");
        BigDecimal formattedOutput = new BigDecimal(decimalFormat.format(number));
        System.out.println(formattedOutput);

In all cases the output will be: 2354548.23

Note:

During rounding you can add RoundingMode in your formatter. Here are some rounding mode given bellow:

    decimalFormat.setRoundingMode(RoundingMode.CEILING);
    decimalFormat.setRoundingMode(RoundingMode.FLOOR);
    decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
    decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
    decimalFormat.setRoundingMode(RoundingMode.UP);

Here are the imports:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

Solution 10 - Java

You can use any one of the below methods

  1. If you are using java.text.DecimalFormat

     DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance(); 
     decimalFormat.setMinimumFractionDigits(2); 
     System.out.println(decimalFormat.format(4.0));
    

OR

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

2. If you want to convert it into simple string format

    System.out.println(String.format("%.2f", 4.0)); 

All the above code will print 4.00

Solution 11 - Java

Works 100%.

import java.text.DecimalFormat;

public class Formatting {

	public static void main(String[] args) {
		double value = 22.2323242434342;
        // or  value = Math.round(value*100) / 100.0;

		System.out.println("this is before formatting: "+value);
		DecimalFormat df = new DecimalFormat("####0.00");
		
		System.out.println("Value: " + df.format(value));
	}

}

Solution 12 - Java

First import NumberFormat. Then add this:

NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();

This will give you two decimal places and put a dollar sign if it's dealing with currency.

import java.text.NumberFormat;
public class Payroll 
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
    int hoursWorked = 80;
    double hourlyPay = 15.52;

    double grossPay = hoursWorked * hourlyPay;
    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();

    System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));
    }

}

Solution 13 - Java

You can do it as follows:

double d = 4.0;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

Solution 14 - Java

I know that this is an old topic, but If you really like to have the period instead of the comma, just save your result as X,00 into a String and then just simply change it for a period so you get the X.00

The simplest way is just to use replace.

String var = "X,00";
String newVar = var.replace(",",".");

The output will be the X.00 you wanted. Also to make it easy you can do it all at one and save it into a double variable:

Double var = Double.parseDouble(("X,00").replace(",",".");

I know that this reply is not useful right now but maybe someone that checks this forum will be looking for a quick solution like this.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristofferView Question on Stackoverflow
Solution 1 - JavakosaView Answer on Stackoverflow
Solution 2 - JavaRohit JainView Answer on Stackoverflow
Solution 3 - JavaVincent Mimoun-PratView Answer on Stackoverflow
Solution 4 - JavaOjonugwa Jude OchalifuView Answer on Stackoverflow
Solution 5 - JavaLewis RobbinsView Answer on Stackoverflow
Solution 6 - JavaMichael ZilbermannView Answer on Stackoverflow
Solution 7 - JavaSubhrajyoti MajumderView Answer on Stackoverflow
Solution 8 - JavaachAmháinView Answer on Stackoverflow
Solution 9 - JavaMd. Sajedul KarimView Answer on Stackoverflow
Solution 10 - JavaFazilView Answer on Stackoverflow
Solution 11 - JavaMayank PariharView Answer on Stackoverflow
Solution 12 - JavaNickView Answer on Stackoverflow
Solution 13 - Javaflosk8View Answer on Stackoverflow
Solution 14 - JavaEdgar RivasView Answer on Stackoverflow