Home Ask Login Register

Developers Planet

Your answer is one click away!

Okiic. February 2016

Rounding errors in Java

I'm having rounding issues in Java (i.e. with whole = 1387.583515625 the output is x = 5836 instead of 5835. I have searched the issue before and I've tried various of the answers but I still can't seem to get it yo work. Any ideas?

DecimalFormat df = new DecimalFormat(".####");

int x = Integer.parseInt(String.format(df.format(whole)).split("\\.")[1]);


Derlin February 2016

This is perfectly well explained in this javadoc.

You need to use RoundingMode.DOWN to get what you want, not RoundingMode.CEILING.

enter image description here

anaxin February 2016

Look at this table to decide what you want https://docs.oracle.com/javase/7/docs/api/java/math/RoundingMode.html


weston February 2016

Be wary of the default locale!

The default locale is not appropriate for machine-readable output.

You're machine reading this formatted output and the problem there is with .split("\\.") in that it assumes the decimal separator is '.'. The fact you specify '.' in the format is neither here nor there, that will get replaced with the separator from the culture.


You can fix by specifying the Locale.US culture, but I'd probably not use string formatting and splitting just to get some of the digits from a number:


int x = (int)((whole - (int)whole) * 10000);


int x = (int)(whole * 10000) % 10000;

And Math.abs if whole might be negative.

Post Status

Asked in February 2016
Viewed 2,073 times
Voted 9
Answered 3 times


Leave an answer

Quote of the day: live life