Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Round to 2 decimal places in Java using DecimalFormat

I am using DecimalFormat to round a value(in Double type) to 2 decimal places

var decimalFormat = new DecimalFormat("0.0");
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
decimalFormat.setMaximumFractionDigits(2);
return decimalFormat.format(value);

When value = 50.275 => result is 50.27
As expected, the result should be 50.28
I have tried using RoundingMode.HALF_EVEN as well but it didn’t work either.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

50.275 cannot be represented exactly and the actual floating point value is something like 50.274999. Thus it is rounded down.

If you have 50.275 as a String, you can create a BigDecimal out of it and format that.

new BigDecimal("50.275").setScale(2, RoundingMode.HALF_UP).toPlainString();
// 50.28
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading