金额操作使用BigDecimal

金额操作使用BigDecimal,使用double的话会有精度损失

MultiCurrencyMoney:

/**

     * 构造器。

     *

     * <p>

     * 创建一个具有金额<code>amount</code>元和指定币种<code>currency</code>的货币对象。

     *

     * @param amount 金额,以元为单位。

     * @param currency 币种。

扫描二维码关注公众号,回复: 637311 查看本文章

     */

    public MultiCurrencyMoney(String amount, Currency currency) {

        this(new BigDecimal(amount), currency);

    }

/**

     * 构造器。

     *

     * <p>

     * 创建一个具有金额<code>amount</code>和指定币种的货币对象。

     * 如果金额不能转换为整数分,则使用四舍五入方式取整。

     *

     * <p>

     * 注意:由于double类型运算中存在误差,使用四舍五入方式取整的

     * 结果并不确定,因此,应尽量避免使用double类型创建货币类型。

     * 例:

     * <code>

     * assertEquals(999, Math.round(9.995 * 100));

     * assertEquals(1000, Math.round(999.5));

     * money = new Money((9.995));

     * assertEquals(999, money.getCent());

     * money = new Money(10.005);

     * assertEquals(1001, money.getCent());

     * </code>

     *

     * @param amount 金额,以元为单位。

     * @param currency 币种。

     */

    public MultiCurrencyMoney(double amount, Currency currency) {

        this.setCurrency(currency);

        //      this.cent = Math.round(amount * getCentFactor());        

        this.cent = Math.round(CheckOverflow.doubleCheckedMultiply(amount, getCentFactor()));

    }

猜你喜欢

转载自xinklabi.iteye.com/blog/2299025