如何使用java BigDecimal类型表示货币值

时间:2021-06-12 16:32:01
public class Product {
    private DoubleProperty unitPrice;  

    public Product() {
        this.unitPrice = new SimpleDoubleProperty();
    }

        public double getUnitPrice() {
        return unitPrice.get();
    }

    public DoubleProperty unitPriceProperty() {
        return unitPrice;
    }

    public void setUnitPrice(double unitPrice) {
        this.unitPrice.set(unitPrice);
    }

    public void setUnitPrice(float unitPrice) {
        this.unitPrice.set(unitPrice);
    }
}

I want to use the BigDecimal type for the model class. What are the lines I should replace to do that? And how should I change the constructor for the BigDecimal item?

我想将BigDecimal类型用于模型类。我应该替换哪些线路?我应该如何更改BigDecimal项的构造函数?

1 个解决方案

#1


1  

public class Product {
    private ObjectProperty<BigDecimal> unitPrice;  

    public Product() {
        this.unitPrice = new SimpleObjectProperty<BigDecimal>();
    }

    public BigDecimal getUnitPrice() {
        return unitPrice.get();
    }

    public ObjectProperty<BigDecimal>unitPriceProperty() {
        return unitPrice;
    }

    public void setUnitPrice(String unitPrice) {
        this.unitPrice.set(new BigDecimal(unitPrice));
    }

    public void setUnitPrice(BigDecimal unitPrice) {
        this.unitPrice.set(unitPrice);
    }
}

The above more or less corresponds to the double-version. Never use BigDecimal constructors with float or double as argument, as those are imprecise numbers without precision; new BigDecimal("3.10") has a scale (precision) of 2.

以上或多或少对应于双版本。永远不要使用带有float或double的BigDecimal构造函数作为参数,因为那些是不精确的不精确数字; new BigDecimal(“3.10”)的比例(精度)为2。

#1


1  

public class Product {
    private ObjectProperty<BigDecimal> unitPrice;  

    public Product() {
        this.unitPrice = new SimpleObjectProperty<BigDecimal>();
    }

    public BigDecimal getUnitPrice() {
        return unitPrice.get();
    }

    public ObjectProperty<BigDecimal>unitPriceProperty() {
        return unitPrice;
    }

    public void setUnitPrice(String unitPrice) {
        this.unitPrice.set(new BigDecimal(unitPrice));
    }

    public void setUnitPrice(BigDecimal unitPrice) {
        this.unitPrice.set(unitPrice);
    }
}

The above more or less corresponds to the double-version. Never use BigDecimal constructors with float or double as argument, as those are imprecise numbers without precision; new BigDecimal("3.10") has a scale (precision) of 2.

以上或多或少对应于双版本。永远不要使用带有float或double的BigDecimal构造函数作为参数,因为那些是不精确的不精确数字; new BigDecimal(“3.10”)的比例(精度)为2。