Java DecimalFormat 保留小数位及四舍五入的陷阱介绍

目录
  • 需求
  • 代码实现
  • 发现问题
  • RoundingMode.HALF_EVEN
  • 错误的代码测试RoundingMode.HALF_EVEN
  • 正确的代码测试RoundingMode.HALF_EVEN
  • 结论

需求

业务需要导出的Excel的数字内容保留两位小数,并且四舍五入

代码实现

百度一圈所抄袭的代码

DecimalFormat dfScale2 = new DecimalFormat("###.##");
dfScale2.format(1.125D);

发现问题

导出数据很诡异.不是所有数据都是如所想的四舍五入.

经过排查最终发现是RoundingMode的问题,应该使用HALF_UP,

DecimalFormat 默认使用的是HALF_EVEN

DecimalFormat dfScale2 = new DecimalFormat("###.##");
System.out.println("dfScale2.getRoundingMode()=" + dfScale2.getRoundingMode());
//输出结果
dfScale2.getRoundingMode()=HALF_EVEN
//

RoundingMode.HALF_EVEN

想了解HALF_EVEN,去官网API看了下

HALF_EVEN 被舍位是5(如保留两位小数的2.115),后面还有非0值进1(如保留两位小数的2.11500001 格式化为2.12),5后面没有数字或者都是0时,前面是偶数则舍,是奇数则进1,目标是让被舍前一位变为偶数.

  • CEILING 向更大的值靠近
  • Rounding mode to round towards positive infinity.
  • DOWN向下取整
  • Rounding mode to round towards zero.
  • FLOOR 向更小的值靠近
  • Rounding mode to round towards negative infinity.
  • HALF_DOWN 五舍六入
  • Rounding mode to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round down.
  • HALF_EVEN
  • Rounding mode to round towards the “nearest neighbor” unless both neighbors are equidistant, in which case, round towards the even neighbor.
  • HALF_UP 四舍五入
  • Rounding mode to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round up.
  • UNNECESSARY 设置这个模式,对于精确值格式化会抛出异常
  • Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.
  • UP 向远离数字0进行进位.
  • Rounding mode to round away from zero.

错误的代码测试RoundingMode.HALF_EVEN

为了更好的理解HALF_EVEN,写了些测试代码但是发现自己更迷惘了…搞不清楚到底HALF_EVEN是什么机制进舍…输出结果的尾数很不规律.

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
public class LocalTest {
//定义一个保留两位小数格式的 DecimalFormat 的变量 dfScale2
 @Test
  public void testDecimalFormat() {
    DecimalFormat dfScale2 = new DecimalFormat("###.##");
    System.out.println("dfScale2.getRoundingMode()=" + dfScale2.getRoundingMode());
    System.out.println("dfScale2.format(1.125D)=" + dfScale2.format(1.125D));
    System.out.println("dfScale2.format(1.135D)=" + dfScale2.format(1.135D));
    System.out.println("dfScale2.format(1.145D)=" + dfScale2.format(1.145D));
    System.out.println("dfScale2.format(1.225D)=" + dfScale2.format(1.225D));
    System.out.println("dfScale2.format(1.235D)=" + dfScale2.format(1.235D));
    System.out.println("dfScale2.format(1.245D)=" + dfScale2.format(1.245D));
    System.out.println();
    System.out.println("dfScale2.format(2.125D)=" + dfScale2.format(2.125D));
    System.out.println("dfScale2.format(2.135D)=" + dfScale2.format(2.135D));
    System.out.println("dfScale2.format(2.145D)=" + dfScale2.format(2.145D));
    System.out.println("dfScale2.format(2.225D)=" + dfScale2.format(2.225D));
    System.out.println("dfScale2.format(2.235D)=" + dfScale2.format(2.235D));
    System.out.println("dfScale2.format(2.245D)=" + dfScale2.format(2.245D));
    System.out.println();
    System.out.println("dfScale2.format(3.125D)=" + dfScale2.format(3.125D));
    System.out.println("dfScale2.format(3.135D)=" + dfScale2.format(3.135D));
    System.out.println("dfScale2.format(3.145D)=" + dfScale2.format(3.145D));
    System.out.println("dfScale2.format(3.225D)=" + dfScale2.format(3.225D));
    System.out.println("dfScale2.format(3.235D)=" + dfScale2.format(3.235D));
    System.out.println("dfScale2.format(3.245D)=" + dfScale2.format(3.245D));
    System.out.println();
    System.out.println("dfScale2.format(4.125D)=" + dfScale2.format(4.125D));
    System.out.println("dfScale2.format(4.135D)=" + dfScale2.format(4.135D));
    System.out.println("dfScale2.format(4.145D)=" + dfScale2.format(4.145D));
    System.out.println("dfScale2.format(4.225D)=" + dfScale2.format(4.225D));
    System.out.println("dfScale2.format(4.235D)=" + dfScale2.format(4.235D));
    System.out.println("dfScale2.format(4.245D)=" + dfScale2.format(4.245D));
  }
 }
dfScale2.getRoundingMode()=HALF_EVEN
dfScale2.format(1.125D)=1.12
dfScale2.format(1.135D)=1.14
dfScale2.format(1.145D)=1.15
dfScale2.format(1.225D)=1.23
dfScale2.format(1.235D)=1.24
dfScale2.format(1.245D)=1.25
dfScale2.format(2.125D)=2.12
dfScale2.format(2.135D)=2.13
dfScale2.format(2.145D)=2.15
dfScale2.format(2.225D)=2.23
dfScale2.format(2.235D)=2.23
dfScale2.format(2.245D)=2.25
dfScale2.format(3.125D)=3.12
dfScale2.format(3.135D)=3.13
dfScale2.format(3.145D)=3.15
dfScale2.format(3.225D)=3.23
dfScale2.format(3.235D)=3.23
dfScale2.format(3.245D)=3.25
dfScale2.format(4.125D)=4.12
dfScale2.format(4.135D)=4.13
dfScale2.format(4.145D)=4.14
dfScale2.format(4.225D)=4.22
dfScale2.format(4.235D)=4.24
dfScale2.format(4.245D)=4.25

正确的代码测试RoundingMode.HALF_EVEN

突然发现自己忽略了一个事情,测试的参数都是用的double类型.想起来double类型不精准.但是侥幸心理以及知识不牢靠以为 3位小数应该影响不大吧.改了下代码,把参数改为BigDecimal类型

使用BigDecimal时,参数尽量传入字符串,要比传入double精准.

new BigDecimal("1.125")
  @Test
  public void testDecimalFormat() {
    DecimalFormat dfScale2 = new DecimalFormat("###.##");
      dfScale2.setRoundingMode(RoundingMode.HALF_EVEN);
    System.out.println("dfScale2.getRoundingMode()=" + dfScale2.getRoundingMode());
        System.out.println("dfScale2.format(new BigDecimal(\"1.1251\"))=" + dfScale2.format(new BigDecimal("1.1251")));
    System.out.println("dfScale2.format(new BigDecimal(\"1.1351\"))=" + dfScale2.format(new BigDecimal("1.1351")));
    System.out.println("dfScale2.format(new BigDecimal(\"1.1451\"))=" + dfScale2.format(new BigDecimal("1.1451")));
    System.out.println("dfScale2.format(new BigDecimal(\"1.2250\"))=" + dfScale2.format(new BigDecimal("1.2250")));
    System.out.println("dfScale2.format(new BigDecimal(\"1.2350\"))=" + dfScale2.format(new BigDecimal("1.2350")));
    System.out.println("dfScale2.format(new BigDecimal(\"1.2450\"))=" + dfScale2.format(new BigDecimal("1.2450")));
    System.out.println("dfScale2.format(new BigDecimal(\"1.22501\"))=" + dfScale2.format(new BigDecimal("1.22501")));
    System.out.println("dfScale2.format(new BigDecimal(\"1.23505\"))=" + dfScale2.format(new BigDecimal("1.23505")));
    System.out.println("dfScale2.format(new BigDecimal(\"1.24508\"))=" + dfScale2.format(new BigDecimal("1.24508")));
dfScale2.getRoundingMode()=HALF_EVEN
dfScale2.format(new BigDecimal("1.1251"))=1.13
dfScale2.format(new BigDecimal("1.1351"))=1.14
dfScale2.format(new BigDecimal("1.1451"))=1.15
dfScale2.format(new BigDecimal("1.2250"))=1.22
dfScale2.format(new BigDecimal("1.2350"))=1.24
dfScale2.format(new BigDecimal("1.2450"))=1.24
dfScale2.format(new BigDecimal("1.22501"))=1.23
dfScale2.format(new BigDecimal("1.23505"))=1.24
dfScale2.format(new BigDecimal("1.24508"))=1.25

结论

1、警觉doulbe的不精确所引起RoundingMode结果不稳定的问题,即使是四舍五入的模式,对double类型参数使用也会有不满足预期的情况.

2、使用数字格式化时,要注意默认RoundingMode模式是否是自己需要的.如果不是记得手动设置下.

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • java保留小数的四种实现方法

    本文实例针对java保留两位小数问题为大家进行解答,供大家参考,具体内容如下 方式一: 四舍五入 double f = 111231.5585; BigDecimal b = new BigDecimal(f); double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); 方式一这个类很好的解决了方式三所带来的问题. 保留两位小数 方式二: DecimalFormat df =new DecimalFormat("#.00

  • java中DecimalFormat四舍五入用法详解

    DecimalFormat 是 NumberFormat 的一个具体子类,用于格式化十进制数字.它可以支持不同类型的数,包括整数 (123).定点数 (123.4).科学记数法表示的数 (1.23E4).百分数 (12%) 和金额 ($123)这些内容的本地化. 下边先介绍下DecimalFormat的用法: import java.text.*; import java.util.*; public class DecimalFormatDemo { public static void ma

  • Java四舍五入时保留指定小数位数的五种方式

    方式一: double f = 3.1516; BigDecimal b = new BigDecimal(f); double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); 输出结果f1为 3.15: 源码解读: public BigDecimal setScale(int newScale, int roundingMode) //int newScale 为小数点后保留的位数, int roundingMode 为变

  • java 四舍五入保留小数的实现方法

    // 方式一: double f = 3.1516; BigDecimal b = new BigDecimal(f); double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); // 方式二: new java.text.DecimalFormat("#.00").format(3.1415926); // #.00 表示两位小数 #.0000四位小数 以此类推- // 方式三: double d = 3.1

  • Java DecimalFormat 保留小数位及四舍五入的陷阱介绍

    目录 需求 代码实现 发现问题 RoundingMode.HALF_EVEN 错误的代码测试RoundingMode.HALF_EVEN 正确的代码测试RoundingMode.HALF_EVEN 结论 需求 业务需要导出的Excel的数字内容保留两位小数,并且四舍五入 代码实现 百度一圈所抄袭的代码 DecimalFormat dfScale2 = new DecimalFormat("###.##"); dfScale2.format(1.125D); 发现问题 导出数据很诡异.不

  • Java Float 保留小数位精度的实现

    目录 Float 保留小数位精度 Float 浮点型数据保留两位小数 1.DecimalFormat 2.Math.round(): Float 保留小数位精度 DecimalFormat decimalFormat=new DecimalFormat(".00"); return Float.valueOf(super.getDecimalFormat().format(new BigDecimal(handleTime))); Float 浮点型数据保留两位小数 用过两种方法:De

  • Java Float 保留小数位精度的实现

    目录 Float 保留小数位精度 Float 浮点型数据保留两位小数 1.DecimalFormat 2.Math.round() Float 保留小数位精度 DecimalFormat decimalFormat=new DecimalFormat(".00"); return Float.valueOf(super.getDecimalFormat().format(new BigDecimal(handleTime))); Float 浮点型数据保留两位小数 用过两种方法:Dec

  • Java中BigDecimal,DateFormatter 和迭代器的"陷阱"

    前言: 使用 IDEA 创建一个 Maven 项目 calculate-date-traps 并导入 Junit 依赖. <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> 在进行计费时使

  • java精度计算代码 java指定精确小数位

    本文实例为大家分享了java指定精确小数位的具体代码,供大家参考,具体内容如下 java代码: public class App2 { public static void main(String[] args) { String val = checkNumber("10.1234155", 2, 6).toString(); System.out.println(val); } public static BigDecimal checkNumber(String number,

  • python3 小数位的四舍五入(用两种方法解决round 遇5不进)

    round( )函数简介 菜鸟教程中介绍到,round() 函数作用就是,返回浮点数x的四舍五入值. > round( x [, n] ) 参数x,n均为数值表达式,返回值为x的四舍五入值.n为保留的小数位数,不加n则只保留x四舍五入后的整数部分. >>> round(2.3) 2 >>> round(2.45, 1) 2.5 特殊情况 上面的结果并没有错误,这里再用2.675测试一下: >>> round(2.675, 2) 2.67 显然结果

  • python保留小数位的三种实现方法

    前言 保留小数位是我们经常会碰到的问题,尤其是刷题过程中.那么在python中保留小数位的方法也非常多,但是笔者的原则就是什么简单用什么,因此这里介绍几种比较简单实用的保留小数位的方法: 方法一:format函数 >>> print('{:.3f}'.format(1.23456)) 1.235 >>> print(format(1.23456, '.2f')) 1.23 正如上面代码所示,format有不同用法,前者使用了占位符{},使用占位符可以同时输出多个,后者一

  • Java强制保留两位小数的四种方法案例详解

    方法一:String的format方法(推荐) double f = 111231.5585; System.out.println(String.format("%.2f", f)); 方法二:DecimalFormat的format方法 double f = 111231.5585; DecimalFormat df = new DecimalFormat("#.00"); System.out.println(df.format(f)); 以下内容了解即可,可

  • 浅谈Java自动装箱与拆箱及其陷阱

    在本文中,笔者向大家介绍下Java中一个非常重要也非常有趣的特性,就是自动装箱与拆箱,并从源码中解读自动装箱与拆箱的原理,同时这种特性也留有一个陷阱.开发者如果不注意,就会很容易跌入这个陷阱. 自动装箱(Autoboxing) 定义 大家在平时编写Java程序时,都常常以以下方式来定义一个Integer对象: Integer i=100; 从上面的代码中,大家可以得知,i为一个Integer类型的引用,100为Java中的基础数据类型(primitive data type).而这种直接将一个基

  • Java编程中避免equals方法的隐藏陷阱介绍

    摘要 本文描述重载equals方法的技术,这种技术即使是具现类的子类增加了字段也能保证equal语义的正确性. 在<Effective Java>的第8项中,Josh Bloch描述了当继承类作为面向对象语言中的等价关系的基础问题,要保证派生类的equal正确性语义所会面对的困难.Bloch这样写到: 除非你忘记了面向对象抽象的好处,否则在当你继承一个新类或在类中增加了一个值组件时你无法同时保证equal的语义依然正确 在<Programming in Scala>中的第28章演示

随机推荐