Reputation: 1552
I have a decimal number 999,999,999,999,999.999 as string from which, i need to remove the commas. For that I am using the following code -
new BigDecimal(NumberFormat.getInstance().parse("999,999,999,999,999.999")
.doubleValue()).setScale(3,BigDecimal.ROUND_HALF_UP);
But this is giving me the rounded value 1000000000000000.000. But what I want is 999999999999999.999. Could anyone please let me how too get this done in java without losing precision. It is not possible what could be the alternate way to do this.
Using replaceAll() on String to replace "," with "" got on my mind but i would like to do it with numbers if it possible.
Thanks in advance.
Upvotes: 3
Views: 4192
Reputation: 420971
You loose the precision when you go via .doubleValue()
.
You need to store it as a BigDecimal
right away. I suggest you use DecimalFormat
and setParseBigDecimal
to true.
DecimalFormat nf = new DecimalFormat("###,###.###");
nf.setParseBigDecimal(true);
BigDecimal bd = ((BigDecimal) nf.parse("999,999,999,999,999.999"))
.setScale(3,BigDecimal.ROUND_HALF_UP);
System.out.println(bd); // 999999999999999.999
Upvotes: 9