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(".####");
df.setRoundingMode(RoundingMode.CEILING);

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

Answers


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

df.setRoundingMode(RoundingMode.HALF_UP);


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.

Alternative

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:

Either:

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

Or:

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

Search




Leave an answer