Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop insignificant zeros when converting a BigDecimal to a String in Java?

java.math.BigDecimal.toString() can return something like "0.888200000". What can be the best I can do if I want "0.8882" instead? I can never know (unless I calculate it for every particular case) the length of the integer (left to the point) part, the value can be 123.8882 as easily as 123456.88.

like image 803
Ivan Avatar asked Feb 06 '12 00:02

Ivan


2 Answers

Use stripTrailingZeros():

Returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.

See http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html

like image 197
The Nail Avatar answered Oct 10 '22 21:10

The Nail


Or, if you fancy regular expressions:

Pattern p = Pattern.compile("(.*?)0*$");
Matcher m = p.matcher(yourString);
String result=m.group(1);

which might be faster than all the messy stuff the BigInteger class does internally in its stripTrailingZeroes method

like image 41
Unai Vivi Avatar answered Oct 10 '22 22:10

Unai Vivi