Stripping trailing zeros in BigDecimal.

Hi,

I am facing a problem while using Bigdecimal. If anyone has faced the same please help.

I want to strip the trailing zeros present in the BigDecimal object.

If I use the stripTrailingZeros() method present in the BigDecimal class, it works well for other values like 1.0 (for which it gives 1) , but for value as 0.0 the method does not strip the trailing zeros

for 0.0 after striping I get the value as again 0.0.

Is there any solution for this ?

Thanks in advance.

[514 byte] By [Hi_i_am_Amita] at [2007-10-3 5:19:44]
# 1

After researching a bit, I got the following solution :

try {

while(true) {

bigDecimal = bigDecimal.setScale(bigDecimal.scale() - 1);

//If the scale becomes 0 then exit from the while loop. This specially happens in case of 0.0

if(bigDecimal.scale() == 0) {

break;

}

}

} catch(ArithmeticException e) {

//no more trailing zeroes so exit.

}

I found this solution in JDC Tech Tips. Hope this helps..

Hi_i_am_Amita at 2007-7-14 23:26:39 > top of Java-index,Java Essentials,Java Programming...
# 2

This smells like a workaround for Java versions prior to 1.5.

IMHO, the original question remains: why stripTrailingZeros() returns a BigInteger with a scale of 1 instead of 0 in this case?

After looking at the source, we can see that the zero case is not taken into account (regardless its initial scale), and is therefore not processed (as absolute unscaled value must be >= 10):private BigDecimal stripZerosToMatchScale(long preferredScale) {

BigInteger qr[];// quotient-remainder pair

while ( intVal.abs().compareTo(BigInteger.TEN) >= 0 &&

scale > preferredScale) {

if (intVal.testBit(0))

break;// odd number cannot end in 0

qr = intVal.divideAndRemainder(BigInteger.TEN);

if (qr[1].signum() != 0)

break;// non-0 remainder

intVal=qr[0];

scale = checkScale((long)scale-1); // could Overflow

if (precision > 0) // adjust precision if known

precision--;

}

return this;

}

I would call it a bug (by omission), don't you?

TimTheEnchantora at 2007-7-14 23:26:39 > top of Java-index,Java Essentials,Java Programming...