zoukankan      html  css  js  c++  java
  • Java DecimalFormat四舍五入的坑及正确用法

    一、DecimalFormat四舍五入的坑

      1.1 有时候我们在处理小数保留几位小数时,想到了DecimalFormat这个类的使用,百度搜一把可能用到以下方式。

    复制代码
     1     public static void main(String[] args) {
     2         String str="3.145";
     3         System.out.println(round1(str));
     4     }
     5 
     6     static String round1(String str){
     7         double a=Double.parseDouble(str);
     8         DecimalFormat df=new DecimalFormat("###.00");
     9         return df.format(a);
    10     }
    复制代码

      1.2 初看好像没什么问题,四舍五入保留两位小数,最后输出3.15。当然精度要求不高,也无需计较。当涉及到精确统计时,这里的坑来了将上面的字符串改为“5”前面为奇数,如“3.155”,就瓜了,输出3.15。显然这里没满足要求,不是我们学校里的四舍五入。再上一段代码。

    1     static String round2(String str){
    2          double a=Double.parseDouble(str);
    3          DecimalFormat df=new DecimalFormat("###.00");
    4          df.setRoundingMode(RoundingMode.HALF_UP);
    5          return df.format(a);
    6     }

      这里可以看到这个setRoundingMode()方法可以设定四舍五入的模式,原来四舍五入不光有我们学校里学的那种,还有其他模式。DecimalFormat默认情况下,它使用 RoundingMode.HALF_EVEN,此舍入模式也称为“银行家舍入法”,主要在美国使用。RoundingMode.HALF_UP这个模式才是我们学校里学的标准四舍五入模式。以上代码虽然舍了学校型模式仍然不准确,应该将double类型改为BigDecimal类型。

    二、学校型四舍五入几种正确使用

      2.1 String直接格式化

    1     static String round3(String str){
    2          double d=Double.parseDouble(str);
    3          return String.format("%.2f",d);
    4     }

      2.2 BigDecimal结合DecimalFormat,BigDecimal比较好性能,数据处理量大不建议使用。

    1     static String round4(String str){
    2          BigDecimal bigDecimal=new BigDecimal(str);
    3          DecimalFormat df=new DecimalFormat("###.00");
    4          df.setRoundingMode(RoundingMode.HALF_UP);
    5          return df.format(bigDecimal);
    6     }

      2.3 BigDecimal单独使用,这个类也自带舍入模式设定方法。

    1     static String round5(String str){
    2          BigDecimal bigDecimal=new BigDecimal(str);
    3          return String.valueOf(bigDecimal.setScale(2,RoundingMode.HALF_UP));
    4     }
  • 相关阅读:
    【Lintcode】112.Remove Duplicates from Sorted List
    【Lintcode】087.Remove Node in Binary Search Tree
    【Lintcode】011.Search Range in Binary Search Tree
    【Lintcode】095.Validate Binary Search Tree
    【Lintcode】069.Binary Tree Level Order Traversal
    【Lintcode】088.Lowest Common Ancestor
    【Lintcode】094.Binary Tree Maximum Path Sum
    【算法总结】二叉树
    库(静态库和动态库)
    从尾到头打印链表
  • 原文地址:https://www.cnblogs.com/fanblogs/p/13474251.html
Copyright © 2011-2022 走看看