Removing trailing zeroes from java.math.BigDecimal produces infinite loop

/**

* Trim all trailing zeros found after the decimal point of {@link java.math.BigDecimal}

* @param n {@link java.math.BigDecimal}

* @return n {@link java.math.BigDecimal}

* <a href="http://groups.google.com/group/comp.lang.java.programmer/browse_frm/thread/5ad5a973fcbf442b/52012c87f1051dd5?lnk=st&q=removing+trailing+zeros+java&rnum=2&hl=en#52012c87f1051dd5">more information</a>

*/

publicstatic BigDecimal trim(BigDecimal n){

try{

while (true){

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

}

}catch (ArithmeticException e){}// DO NOTHING NO MORE TRAILING ZEROS FOUND

return n;

}

This method is supposed to remove any and all trailing zeroes from a given java.math.BigDecimal parameter n and return it "trimmed".

However, if n < 1 or n > -1 the method goes into an infinite loop. Not sure how to patch this method to prevent this from occurring from this condition. What tips do you have to prevent this from occurring? I thought of BigDecimal.ROUND_HALF_UP, but to no avail.

Thanx

Phil

[1624 byte] By [ppowell777a] at [2007-11-26 17:21:58]
# 1
hmmyou use while(true) and you wonder why you have an inf loop? maybe you should come up with a better algorithm. or maybe use NumberFormat
mkoryaka at 2007-7-8 23:49:57 > top of Java-index,Java Essentials,New To Java...
# 2
not to mention that it is usually bad to use exceptions as a main method of flow control. they are called exceptions for the reason that they shouldnt happen.
mkoryaka at 2007-7-8 23:49:57 > top of Java-index,Java Essentials,New To Java...
# 3

> hmm

>

> you use while(true) and you wonder why you have an

> inf loop?

Yes. Because if the number is > 1 or < -1, it ends just fine. Only goes infinite between -1 and 1.

>

> maybe you should come up with a better algorithm. or

> maybe use NumberFormat

I didn't come up with this original format, I "borrowed" from comp.lang.java.help Google groups as I don't know of any way to "trim" a BigDecimal

ppowell777a at 2007-7-8 23:49:57 > top of Java-index,Java Essentials,New To Java...
# 4
Check the scale() before hand and set an appropriate increment, it's not like you don't have any way of knowing the case you have before hand.
morgalra at 2007-7-8 23:49:57 > top of Java-index,Java Essentials,New To Java...
# 5
See function stripTrailingZeros() @ http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.htmlCheers
duckbilla at 2007-7-8 23:49:57 > top of Java-index,Java Essentials,New To Java...
# 6
> No need to reinvent the wheel? See function> stripTrailingZeros() @> http://java.sun.com/javase/6/docs/api/java/math/BigDec> imal.htmlNext time I'll just ask here and stop relying on Google Groups for anything. Thanks
ppowell777a at 2007-7-8 23:49:57 > top of Java-index,Java Essentials,New To Java...