Okiic.
Okiic.

Reputation: 117

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

Upvotes: 0

Views: 98

Answers (3)

weston
weston

Reputation: 54791

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.

Upvotes: 1

anaxin
anaxin

Reputation: 710

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

Upvotes: 3

Derlin
Derlin

Reputation: 9881

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

Upvotes: 1

Related Questions