在 java 中传递 bigdecimal 数字

pass bigdecimal numbers in java

我想将值传递给使用大十进制数的方法,但我的程序显示编译器错误。

package com.khalidFarik;

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        checknumbersinDecimals(12.3,12.2);
    }

    public static void checknumbersinDecimals(BigDecimal payment1,BigDecimal payment2){
        payment1 = new BigDecimal("1230.23");
        payment2 = new BigDecimal("1230.23");
        BigDecimal number3= payment1.subtract(payment2);
        System.out.println(number3.toString());
    }
}

如何在 main 方法中将大十进制数传递给我的方法 checknumbersinDecimals()

BigDecimal 对象传递给方法类似于传递任何其他 Object 引用。创建一个新的 BigDecimal 对象并将其作为引用传递。您可以使用以下语法

checknumbersinDecimals(new BigDecimal(12.3),new BigDecimal(12.2));

12.3 表示 double 值。将其作为 new BigDecimal(12.3) 的构造函数值传递为其创建 BigDecimal 引用

您的方法接受 BigDecimal 作为参数,但您传递的是 12.3,12.2 - 这是 double 而不是 BigDecimal

您将 BigDecimal 对象作为参数而不是 double 传递,如下所示:

checknumbersinDecimals(new BigDecimal(String.valueOf(12.3)),new BigDecimal(String.valueOf(12.2)));

注意: 使用BigDecimal(String) constructor instead of BigDecimal(double) constructor as by using the latter, you could lose precision. The caution as rightly mentioned in the doc:

  • The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
  • The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
  • When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.

BigDecimal.valueOf(double) 是建议使用而不是构造函数 new BigDecimal(),它会准确地为您提供传入的值。

checknumbersinDecimals(BigDecimal.valueOf(12.3), BigDecimal.valueOf(12.2));