本文介绍了为什么新的BigDecimal(“0.0”)。stripTrailingZeros()的比例为1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行这个简单的程序:

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());
}

输出:

0
0
1
0

我的问题很简单:为什么第三个 println 输出 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:

事实上,它适用于任意数量的零: new BigDecimal(0.0000)。stripTrailingZeroes()。scale()是4!

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

推荐答案

实际上0.0是例外,因为它没有stripTrailingZeroes。
一个错误!

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






已在Java 8中修复! 请参阅@ vadim_shb的评论。


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

这篇关于为什么新的BigDecimal(“0.0”)。stripTrailingZeros()的比例为1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 18:13