Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does new BigDecimal("0.0").stripTrailingZeros() have a scale of 1?

Running this simple program:

public static void main(final String... args)
{
    System.out.println(BigDecimal.ZERO.scale());
    System.out.println(new BigDecimal("0").scale());
    System.out.println(new BigDecimal("0.0").stripTrailingZeros().scale());
    System.out.println(new BigDecimal("1.0").stripTrailingZeros().scale());
}

outputs:

0
0
1
0

My question is rather simple: why doesn't the third println output 0? That would seem logical...

EDIT: OK, so, this is a very old bug:

Bug Link

and in fact, it "works" for any number of zeroes: new BigDecimal("0.0000").stripTrailingZeroes().scale() is 4!

like image 839
fge Avatar asked Feb 08 '13 12:02

fge


People also ask

What is BigDecimal scale?

A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.

How do I remove trailing zeros from BigDecimal?

stripTrailingZeros() is an inbuilt method in Java that returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. So basically the function trims off the trailing zero from the BigDecimal value.

What is the value of BigDecimal zero?

BigDecimal is zero means that it can store 0, 0.0 or 0.00 etc values.


1 Answers

In fact "0.0" is the exception as it does no stripTrailingZeroes. A bug!

public static void main(final String... args) {
    p("0");
    p("0.0");
    p("1.0");
    p("1.00");
    p("1");
    p("11.0");
}

private static void p(String s) {
    BigDecimal stripped = new BigDecimal(s).stripTrailingZeros();
    System.out.println(s + " - scale: " + new BigDecimal(s).scale()
        + "; stripped: " + stripped.toPlainString() + " " + stripped.scale());
}

0 - scale: 0; stripped: 0 0
0.0 - scale: 1; stripped: 0.0 1
1.0 - scale: 1; stripped: 1 0
1.00 - scale: 2; stripped: 1 0
1 - scale: 0; stripped: 1 0
11.0 - scale: 1; stripped: 11 0

Fixed in Java 8! See @vadim_shb's comment.

like image 117
Joop Eggen Avatar answered Sep 28 '22 11:09

Joop Eggen