Java舍入到小数点后15位

时间:2016-09-19 04:44:08

标签: java rounding rounding-error

我有以下代码将远期汇率四舍五入到15位小数。当_ForwardRate为13,555.0时,结果返回错误。

public double round(double Number, int Decimal_Place) {     
    if (Number==0) return 0;
    double _plug = 0.000001;
    if (Number < 0) {
        _plug = -0.000001;
    }
    //Sometime a number is rounded down to 2.22499999999 by java. 
    //Actual precision is 2.245.  Without this plug, a 2 dp rounding result
    //in 2.22 when it should be 2.23
    double _newNumber = Number;
    if (Decimal_Place==2) {
        _newNumber = _newNumber+_plug;      
    }

    double _number_abs = Math.abs(_newNumber);  
    double _factor = Math.pow(10, Decimal_Place);
    double _rd = Math.round(_number_abs * _factor);
    double _r = _rd/_factor;
    if (Number <= 0)
        _r = _r * -1;

    return _r;
}

Double _ForwardRate = getForward_rate();
BigDecimal _fwdrate_bd = BigDecimal.valueOf(_ForwardRate.doubleValue());
_ForwardRate = round(new Double(_fwdrate_bd.doubleValue()), 15);

当前结果

9,223.372036854777

预期结果

13,555.000000000000000

2 个答案:

答案 0 :(得分:1)

您的问题是Math.round(double a)返回 long ,而您溢出

一种简单的方法是使用BigDecimal

public static double round(double number, int decimalPlaces) {
    return BigDecimal.valueOf(number)
                     .setScale(decimalPlaces, RoundingMode.HALF_UP)
                     .doubleValue();
}

这允许您控制舍入模式。请注意,Math.round()完成的舍入为HALF_CEILING setScale()不支持。

如果您需要这种精确度,您可能需要考虑使用BigDecimal完成所有数学运算。

答案 1 :(得分:0)

考虑:

    double _factor = Math.pow(10, Decimal_Place);

此时,_factor包含值13555.0

1.0E15

现在 double _rd = Math.round(_number_abs * _factor); 包含Math.round()

_number_abs * _factor

根据Javadoc

  

1.3555E19返回与参数最接近的长度,并将关系舍入为正无穷大。

由于Long.MAX_VALUELong.MAX_VALUE,大于Long,结果为@Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; View view = convertView; if (view == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.genre_list_text, parent, false); viewHolder = new ViewHolder(); holder.text1=(TextView) view.findViewById(R.id.text1); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } holder.text1.setText(names[position]); return view; } ,即与给定值“最接近”please try this code its workin fine echo '<button onclick="window.location.href=\'save.php?myDocRegNo='.$A.'&docCat='.$C.'&dcrNo='.$Dcr_No.'&metTown='.$Town_Code.'&dcrDate='.$Dcr_Date.'&repCode='.$Rep_Code.'&db='.$Dbase.'&fullTown='.$Town.'&fullRep='.$FlRp.'\'">Continue</button>';