[java] Double decimal formatting in Java

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?

This question is related to java formatting double decimal

The answer is


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.


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

}

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;

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


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

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


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

You can do it as follows:

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

Use String.format:

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

As per docs:

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


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

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


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

}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to double

Round up double to 2 decimal places Convert double to float in Java Float and double datatype in Java Rounding a double value to x number of decimal places in swift How to round a Double to the nearest Int in swift? Swift double to string How to get the Power of some Integer in Swift language? Difference between int and double How to cast the size_t to double or int C++ How to get absolute value from double - c-language

Examples related to decimal

Java and unlimited decimal places? What are the parameters for the number Pipe - Angular 2 Limit to 2 decimal places with a simple pipe C++ - Decimal to binary converting Using Math.round to round to one decimal place? String to decimal conversion: dot separation instead of comma Python: Remove division decimal Converting Decimal to Binary Java Check if decimal value is null Remove useless zero digits from decimals in PHP