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("\\."));
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.
Asked in February 2016Viewed 2,073 timesVoted 9Answered 3 times