Tuesday, 20 August 2013

Formatting Decimal Number

Formatting Decimal Number

I am formatting decimal number and I have the following criteria to format
it:
Number should be atmost two decimal places (10.1234=>10.12)
If there is only one digit after decimal then it will ends up with 0
(10.5=>10.50)
Thousand separator will be comma (12345.2345 => 12,345.23)
I have written following logic:
double x = Double.parseDouble(value.toString());
String dec = x % 1 == 0 ? new
java.text.DecimalFormat("###,###.##").format(x) : new
java.text.DecimalFormat("###,###.00").format(x);
Now it is printing:
11111111111110.567=>11,111,111,111,110.57
111111111111110.567=>111,111,111,111,110.56
1111111111111110.567=>1,111,111,111,111,110.60
11111111111111110.567=>11,111,111,111,111,110
111111111111111110.567=>111,111,111,111,111,104
1111111111111111110.567=>1,111,111,111,111,111,170
I don't understand why the behavior changes. If I what to print
1111111111111111110.567 as 1,111,111,111,111,111,110.57 what should I do?

No comments:

Post a Comment