Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

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

807599Feb 5 2007 — edited Feb 5 2007
 /**
     * 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>
     */
    public static 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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 5 2007
Added on Feb 5 2007
6 comments
1,500 views