java四舍五入方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuanzhangran/article/details/77098041

题目要求:
(1)0.01-99.99:在毫位上四舍五入,保留两位小数,如10.235元,处理为10.24元;10.231元,处理为10.23元。
(2)100.00-999.99:在分位上四舍五入,保留2位小数,分位上变为0。如100.35元,处理为100.40元;100.21元,处理为100.20元;100.95元,处理为101.00。
(3)1000.00以上:在角位上四舍五入,保留两位小数,分位上变为0。如1000.98元,处理为1001.00元;1000.42元,处理为1000.00元。

//方法1:
import java.math.BigDecimal;
import java.text.DecimalFormat;
public static String returnMoney(double money){
        if(money>0&&money<100){
             money = MathUtil.round(money,2);//毫位
         }else if(money>=100&&money<1000){
             money = MathUtil.round(money,1);//分位
         }else if(money>1000){
             money = MathUtil.round(money,0);//角位
         }
         DecimalFormat df = new DecimalFormat("##0.00");
         return df.format(money);
}
//工具类:
public class MathUtil { 
    public static double round(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
//调用
public static void main(String[] args) {
      System.out.println(returnMoney(100.95));
 }

/////////////////////////////////////////////////////////////////////

//方法2:
//money表示要四舍五入的数,i表示在第几位四舍五入
  import java.math.BigDecimal;
  import java.text.DecimalFormat;
  public Double returnMoney(Double money,int i){
    BigDecimal   b   =   new   BigDecimal(money);
    double   f1   =   b.setScale(i,   RoundingMode.HALF_UP).doubleValue();
   }
    public static void main(String[] args){
    Double money = 100.95;
    if(0 < money <= 100){
        money = returnMoney(money,2);
    }
    .......(省略其他)
    if(money < 0 ){
        System.out.print("输入错误!")
    }
  }

猜你喜欢

转载自blog.csdn.net/xuanzhangran/article/details/77098041
今日推荐