Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

java - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...