In many real-world Java applications, we often need to round numbers—for example, displaying prices in an e-commerce website or calculating salary amounts in a payroll system. In this article, we explore various ways to round double or float values to 2 decimal places. We will cover methods using DecimalFormat, BigDecimal, String.format, and Math.round, so we can choose the best approach based on our needs.
Table of Contents
- 1. DecimalFormat("0.00")
- 2. DecimalFormat("0.00") vs DecimalFormat("#.##")
- 3. Using BigDecimal
- 4. Using String.format("%.2f", input)
- 5. Using Math.round
- 6. References
Note:
For monetary calculations where precision is critical, we recommend using BigDecimal. For display purposes where a fixed format is required, DecimalFormat("0.00") is often the better choice.
1. DecimalFormat(“0.00”)
We can use DecimalFormat("0.00") to ensure that a number always rounds to 2 decimal places. By default, DecimalFormat uses RoundingMode.HALF_EVEN, but we can change the rounding mode using setRoundingMode(RoundingMode) if needed. For instance, when displaying a salary in our payroll application, we want to ensure the value is consistently formatted.
package com.mkyong.math.rounding;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalExample {
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) {
double input = 1205.6358;
System.out.println("Original value : " + input);
// Using DecimalFormat with the default RoundingMode.HALF_EVEN
System.out.println("Rounded (HALF_EVEN) : " + df.format(input)); // 1205.64
// Changing to RoundingMode.DOWN
df.setRoundingMode(RoundingMode.DOWN);
System.out.println("Rounded (DOWN) : " + df.format(input)); // 1205.63
// Changing to RoundingMode.UP
df.setRoundingMode(RoundingMode.UP);
System.out.println("Rounded (UP) : " + df.format(input)); // 1205.64
}
}
Output:
Original value : 1205.6358
Rounded (HALF_EVEN) : 1205.64
Rounded (DOWN) : 1205.63
Rounded (UP) : 1205.64
2. DecimalFormat(“0.00”) vs DecimalFormat(“#.##”)
It is important to understand the difference between DecimalFormat("0.00") and DecimalFormat("#.##"). When formatting numbers for display, trailing zeros can be significant. For example, in a financial report, we want to show two decimal places even if the number is whole.
package com.mkyong.math.rounding;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalExample2 {
private static final DecimalFormat dfZero = new DecimalFormat("0.00");
private static final DecimalFormat dfSharp = new DecimalFormat("#.##");
public static void main(String[] args) {
double input = 1205.6;
System.out.println("Original value : " + input);
System.out.println("Using 0.00 : " + dfZero.format(input)); // Displays 1205.60
System.out.println("Using #.## : " + dfSharp.format(input)); // Displays 1205.6
double input2 = 1205.60;
System.out.println("\nOriginal value : " + input2);
System.out.println("Using 0.00 : " + dfZero.format(input2)); // Displays 1205.60
System.out.println("Using #.## : " + dfSharp.format(input2)); // Displays 1205.6
}
}
Output:
Original value : 1205.6
Using 0.00 : 1205.60
Using #.## : 1205.6
Original value : 1205.6
Using 0.00 : 1205.60
Using #.## : 1205.6
In scenarios where a consistent two-decimal display is required, such as in invoices or price tags, we recommend using DecimalFormat("0.00").
3. Using BigDecimal
For applications that require high precision, such as financial systems calculating interest or tax, we often use BigDecimal. This approach gives us more control over the rounding mechanism and minimizes errors caused by floating-point arithmetic.
package com.mkyong.math.rounding;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalExample {
public static void main(String[] args) {
double input = 1205.6358;
System.out.println("Original double value : " + input);
// Convert double to BigDecimal
BigDecimal salary = new BigDecimal(input);
System.out.println("BigDecimal value : " + salary);
// Round to 2 decimal places using RoundingMode.HALF_UP
BigDecimal salaryRounded = salary.setScale(2, RoundingMode.HALF_UP);
System.out.println("Rounded BigDecimal value : " + salaryRounded);
// One-line conversion and rounding
BigDecimal salaryOneLine = new BigDecimal(input).setScale(2, RoundingMode.HALF_UP);
System.out.println("One-line rounded BigDecimal : " + salaryOneLine);
// Convert BigDecimal back to double
double roundedDouble = salaryOneLine.doubleValue();
System.out.println("Rounded double value : " + roundedDouble);
}
}
Output:
Original double value : 1205.6358
BigDecimal value : 1205.63580000000001746229827404022216796875
Rounded BigDecimal value : 1205.64
One-line rounded BigDecimal : 1205.64
Rounded double value : 1205.64
This method is especially useful when we deal with monetary values in a banking or e-commerce application where rounding errors can be critical.
4. Using String.format(“%.2f”, input)
Another simple approach for rounding numbers is by using String.format. This method is excellent for displaying rounded values, such as when showing product prices on a website. However, note that we cannot change the rounding mode—it always rounds using half-up by default.
package com.mkyong.math.rounding;
public class StringFormatExample {
public static void main(String[] args) {
double input = 1205.6358;
System.out.println("Original value : " + input);
// Using String.format to round to 2 decimal places
System.out.println("Rounded value : " + String.format("%.2f", input));
System.out.format("Rounded value : %.2f", input);
}
}
Output:
Original value : 1205.6358
Rounded value : 1205.64
Rounded value : 1205.64
5. Using Math.round
We also have the option of using Math.round for rounding numbers, which is helpful for educational purposes and simple rounding tasks. For example, if we want to calculate the final price of an item including tax, this method might come in handy.
5.1 Rounding to 2 Decimal Places
package com.mkyong.math.rounding;
public class MathExample {
public static void main(String[] args) {
double input = 1205.6358;
System.out.println("Original value : " + input);
double roundedSalary = Math.round(input * 100.0) / 100.0;
System.out.println("Rounded value : " + roundedSalary);
}
}
Output:
Original value : 1205.6358
Rounded value : 1205.64
5.2 Rounding to 3 Decimal Places
For situations where we need more precision, such as scientific calculations, we can adjust the multiplier accordingly:
double input = 1205.6358;
double roundedValue = Math.round(input * 1000.0) / 1000.0;
System.out.println("Rounded value : " + roundedValue);
Output:
Original value : 1205.6358
Rounded value : 1205.636
I created an account just to say thank you.
Thank you much…DecimalFormat is really good solution.
It is better than Math.Round!
(12465,2) than it gives 12500 and (12465,3) than it gives 12000 can any one have idea to write such method.in java
this question was asked to me at interview.
Hi Senior programmer, I am glad you shared your ideas online for us to learn. Well done sir.
DecimalFormat df = new DecimalFormat(“0.00”);
double time = 1205.00;
time = Double.valueOf(df.format(time));
System.out.println(time);
// output 1205.0 but expect 1205.00
is DecimalFormat class name? Please reply asap
Need DecimalFormat for display in 2 decimal points.
System.out.println(ft.format(time)); // output 1205.00
First: Math.round(123.50 * 100.0) = 124.0, ok.
Second: Math.round(-123.50 * 100.0) = -123.0!! is this correct?, I wait -124.0.
Isn’t nearest number -124.0 to -123.50?
I had the same issue, Math.round method is overloaded and you are getting the long back make sure you pick the method that returns an int.
please can we do this format like 1,200.00 is yes any ideas to share, please
THANKS HELPED OUT!!
good good
Thanks for this. Its useful. Saved sometime. You are hero.
In DecimalFormat(“0.00”) or DecimalFormat(“#.##”) ??
In DecimalFormat we should use 0 or # ??
For 1205.61
#.## display 1205.61
0.00 display 1205.61
For 1205.60
#.## display 1205.6
0.00 display 1205.60
For 1205.6
#.## display 1205.6
0.00 display 1205.60
int i = 180;
int j = 1;
double div= ((double)(j*100)/i);
DecimalFormat df = new DecimalFormat(“#.00”); // simple way to format till any deciaml points
System.out.println(div);
System.out.println(df.format(div));
EditText GridBase = (EditText) findViewById(R.id.GridBase);
Double GridBasedbl = Double.parseDouble(GridBase.getText().toString());
//
TextView VoltageBase = (TextView) findViewById(R.id.VoltageBase);
Double VoltageBasedbl = Double.parseDouble(VoltageBase.getText().toString());
//
Double product = GridBasedbl*VoltageBasedbl;
Log.d(“Calc product”, Double.toString(product));
EditText GridVoltage = (EditText) findViewById(R.id.GridVoltage);
GridVoltage.setText(String.format(“%.3f”, product));
Log.d(“Calc GridVoltage”, GridVoltage.getText().toString());
i want to convert -0.00000000758602002145 to zero in two decimal accuracy.
double kilobytes = -0.00000000758602002145;
DecimalFormat df = new DecimalFormat(“###.##”);
System.out.println(“kilobytes (DecimalFormat) : ” + df.format(kilobytes));
the result i got is “-0”
What to do … ?
Please refer that
double lvForeignPremiumAmount=6208.125
System.out.println(“AFT Math.round(lvForeignPremiumAmount*100.0)/100.0 =”+Math.round(lvForeignPremiumAmount*100.0)/100.0);
System.out.println(“AFT formatter.format(lvForeignPremiumAmount)=”+formatter.format(lvForeignPremiumAmount));
Therefor Please advice which method could be more accurate.
I want to convert value like 5.8987221219522616E-5…want to avoid E value..please let me know if have any idea about it…thanks
man, thank you so much.
Saved me a lot of time. Most didatic explanation i’ve found.
Keep up with the good work, bye.
thanks for that tip
very helpful
millions of Thanks