java四舍五入方法

来源:互联网 发布:安徽综艺频道网络电视 编辑:程序博客网 时间:2024/06/02 05:09

题目要求:
(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("输入错误!")    }  }
原创粉丝点击