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

前端 未结 1 1805
一个人的身影
一个人的身影 2020-12-01 18:30

Running this simple program:

public static void main(final String... args)
{
    System.out.println(BigDecimal.ZERO.scale());
    System.out.println(new BigD         


        
相关标签:
1条回答
  • 2020-12-01 19:07

    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.

    0 讨论(0)
提交回复
热议问题