本文介绍了在BigDecimal中找到有效位数的巧妙方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想限制BigDecimal中的有效位数.我只想查找该数字具有的有效位数.

I do not want to limit the number of significant digits in a BigDecimal. I only want to find the number of significant digits that number has.

有没有一种方法,而无需将数字转换为字符串并计算数字字符?

Is there a way to do this without converting the number to string and count the number characters?

推荐答案

我相信您需要 stripTrailingZeros precision scale ,如此处所示:

I believe you want a combination of stripTrailingZeros, precision and scale, as demonstrated here:

import java.math.*;

public class Test {

    public static void main(String[] args) {
        test("5000");      // 4
        test("5000.00");   // 4
        test("5000.12");   // 6
        test("35000");     // 5
        test("35000.00");  // 5
        test("35000.12");  // 7
        test("35000.120"); // 7
        test("0.0034");    // 2
        test("1.0034");    // 5
        test("1.00340");   // 5
    }


    private static void test(String input) {
        System.out.println(input + " => " +
            significantDigits(new BigDecimal(input)));
    }

    private static int significantDigits(BigDecimal input) {
        input = input.stripTrailingZeros();
        return input.scale() < 0
            ? input.precision() - input.scale()
            : input.precision();
    }
}

需要调用stripTrailingZeros,否则BigDecimal完全有可能以非规范"形式存储.例如,new BigDecimal(5000)的精度为4,而不是1.

The call to stripTrailingZeros is required as otherwise it's entirely possible for a BigDecimal to be stored in a "non-normalized" form. For example, new BigDecimal(5000) has a precision of 4, not 1.

scale()的调用用于处理规范化形式在小数点前 但小数点后 没有尾随零的情况.在这种情况下,小数位将始终为负,并指示尾随零的数量.

The call to scale() is used to handle cases where the normalized form has trailing zeroes before the decimal point, but nothing after the decimal point. In this case, the scale will always be negative, and indicates the number of trailing zeroes.

带有尾随零但不带小数点的情况本质上是模棱两可的-例如,没有确定数量的有效数字到"5000".上面的代码将小数点前的所有尾随零都视为有效.

Cases with trailing zeroes but no decimal point are inherently ambiguous - there's no definite number of significant digits to "5000" for example. The above code treats all trailing zeroes before the decimal point as significant.

这篇关于在BigDecimal中找到有效位数的巧妙方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:55
查看更多