BigDecimal 小数位的处理(RoundingMode)

2024-06-24 03:36

本文主要是介绍BigDecimal 小数位的处理(RoundingMode),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言:

在日常项目开发中,接触小数是常有的事情,而产品对于小数的处理,在不同的业务中有不同的定义,比如四舍五入、截取、向上舍位、向下舍位等等场景,面对如此多的场景,你是否会束手无策?或者说自己去研究怎么实现?其实 Java 已经给我们提供了一个枚举类 RoundingMode,RoundingMode 共有 8 种舍位方式,本篇我们来逐个分析。

RoundingMode 枚举类源码如下:

package java.math;/**** @see     BigDecimal* @see     MathContext* @author  Josh Bloch* @author  Mike Cowlishaw* @author  Joseph D. Darcy* @since 1.5*/
public enum RoundingMode {/*** Rounding mode to round away from zero.  Always increments the* digit prior to a non-zero discarded fraction.  Note that this* rounding mode never decreases the magnitude of the calculated* value.**<p>Example:*<table border>* <caption><b>Rounding mode UP Examples</b></caption>*<tr valign=top><th>Input Number</th>*    <th>Input rounded to one digit<br> with {@code UP} rounding*<tr align=right><td>5.5</td>  <td>6</td>*<tr align=right><td>2.5</td>  <td>3</td>*<tr align=right><td>1.6</td>  <td>2</td>*<tr align=right><td>1.1</td>  <td>2</td>*<tr align=right><td>1.0</td>  <td>1</td>*<tr align=right><td>-1.0</td> <td>-1</td>*<tr align=right><td>-1.1</td> <td>-2</td>*<tr align=right><td>-1.6</td> <td>-2</td>*<tr align=right><td>-2.5</td> <td>-3</td>*<tr align=right><td>-5.5</td> <td>-6</td>*</table>*/UP(BigDecimal.ROUND_UP),/*** Rounding mode to round towards zero.  Never increments the digit* prior to a discarded fraction (i.e., truncates).  Note that this* rounding mode never increases the magnitude of the calculated value.**<p>Example:*<table border>* <caption><b>Rounding mode DOWN Examples</b></caption>*<tr valign=top><th>Input Number</th>*    <th>Input rounded to one digit<br> with {@code DOWN} rounding*<tr align=right><td>5.5</td>  <td>5</td>*<tr align=right><td>2.5</td>  <td>2</td>*<tr align=right><td>1.6</td>  <td>1</td>*<tr align=right><td>1.1</td>  <td>1</td>*<tr align=right><td>1.0</td>  <td>1</td>*<tr align=right><td>-1.0</td> <td>-1</td>*<tr align=right><td>-1.1</td> <td>-1</td>*<tr align=right><td>-1.6</td> <td>-1</td>*<tr align=right><td>-2.5</td> <td>-2</td>*<tr align=right><td>-5.5</td> <td>-5</td>*</table>*/DOWN(BigDecimal.ROUND_DOWN),/*** Rounding mode to round towards positive infinity.  If the* result is positive, behaves as for {@code RoundingMode.UP};* if negative, behaves as for {@code RoundingMode.DOWN}.  Note* that this rounding mode never decreases the calculated value.**<p>Example:*<table border>* <caption><b>Rounding mode CEILING Examples</b></caption>*<tr valign=top><th>Input Number</th>*    <th>Input rounded to one digit<br> with {@code CEILING} rounding*<tr align=right><td>5.5</td>  <td>6</td>*<tr align=right><td>2.5</td>  <td>3</td>*<tr align=right><td>1.6</td>  <td>2</td>*<tr align=right><td>1.1</td>  <td>2</td>*<tr align=right><td>1.0</td>  <td>1</td>*<tr align=right><td>-1.0</td> <td>-1</td>*<tr align=right><td>-1.1</td> <td>-1</td>*<tr align=right><td>-1.6</td> <td>-1</td>*<tr align=right><td>-2.5</td> <td>-2</td>*<tr align=right><td>-5.5</td> <td>-5</td>*</table>*/CEILING(BigDecimal.ROUND_CEILING),/*** Rounding mode to round towards negative infinity.  If the* result is positive, behave as for {@code RoundingMode.DOWN};* if negative, behave as for {@code RoundingMode.UP}.  Note that* this rounding mode never increases the calculated value.**<p>Example:*<table border>* <caption><b>Rounding mode FLOOR Examples</b></caption>*<tr valign=top><th>Input Number</th>*    <th>Input rounded to one digit<br> with {@code FLOOR} rounding*<tr align=right><td>5.5</td>  <td>5</td>*<tr align=right><td>2.5</td>  <td>2</td>*<tr align=right><td>1.6</td>  <td>1</td>*<tr align=right><td>1.1</td>  <td>1</td>*<tr align=right><td>1.0</td>  <td>1</td>*<tr align=right><td>-1.0</td> <td>-1</td>*<tr align=right><td>-1.1</td> <td>-2</td>*<tr align=right><td>-1.6</td> <td>-2</td>*<tr align=right><td>-2.5</td> <td>-3</td>*<tr align=right><td>-5.5</td> <td>-6</td>*</table>*/FLOOR(BigDecimal.ROUND_FLOOR),/*** Rounding mode to round towards {@literal "nearest neighbor"}* unless both neighbors are equidistant, in which case round up.* Behaves as for {@code RoundingMode.UP} if the discarded* fraction is &ge; 0.5; otherwise, behaves as for* {@code RoundingMode.DOWN}.  Note that this is the rounding* mode commonly taught at school.**<p>Example:*<table border>* <caption><b>Rounding mode HALF_UP Examples</b></caption>*<tr valign=top><th>Input Number</th>*    <th>Input rounded to one digit<br> with {@code HALF_UP} rounding*<tr align=right><td>5.5</td>  <td>6</td>*<tr align=right><td>2.5</td>  <td>3</td>*<tr align=right><td>1.6</td>  <td>2</td>*<tr align=right><td>1.1</td>  <td>1</td>*<tr align=right><td>1.0</td>  <td>1</td>*<tr align=right><td>-1.0</td> <td>-1</td>*<tr align=right><td>-1.1</td> <td>-1</td>*<tr align=right><td>-1.6</td> <td>-2</td>*<tr align=right><td>-2.5</td> <td>-3</td>*<tr align=right><td>-5.5</td> <td>-6</td>*</table>*/HALF_UP(BigDecimal.ROUND_HALF_UP),/*** Rounding mode to round towards {@literal "nearest neighbor"}* unless both neighbors are equidistant, in which case round* down.  Behaves as for {@code RoundingMode.UP} if the discarded* fraction is &gt; 0.5; otherwise, behaves as for* {@code RoundingMode.DOWN}.**<p>Example:*<table border>* <caption><b>Rounding mode HALF_DOWN Examples</b></caption>*<tr valign=top><th>Input Number</th>*    <th>Input rounded to one digit<br> with {@code HALF_DOWN} rounding*<tr align=right><td>5.5</td>  <td>5</td>*<tr align=right><td>2.5</td>  <td>2</td>*<tr align=right><td>1.6</td>  <td>2</td>*<tr align=right><td>1.1</td>  <td>1</td>*<tr align=right><td>1.0</td>  <td>1</td>*<tr align=right><td>-1.0</td> <td>-1</td>*<tr align=right><td>-1.1</td> <td>-1</td>*<tr align=right><td>-1.6</td> <td>-2</td>*<tr align=right><td>-2.5</td> <td>-2</td>*<tr align=right><td>-5.5</td> <td>-5</td>*</table>*/HALF_DOWN(BigDecimal.ROUND_HALF_DOWN),/*** Rounding mode to round towards the {@literal "nearest neighbor"}* unless both neighbors are equidistant, in which case, round* towards the even neighbor.  Behaves as for* {@code RoundingMode.HALF_UP} if the digit to the left of the* discarded fraction is odd; behaves as for* {@code RoundingMode.HALF_DOWN} if it's even.  Note that this* is the rounding mode that statistically minimizes cumulative* error when applied repeatedly over a sequence of calculations.* It is sometimes known as {@literal "Banker's rounding,"} and is* chiefly used in the USA.  This rounding mode is analogous to* the rounding policy used for {@code float} and {@code double}* arithmetic in Java.**<p>Example:*<table border>* <caption><b>Rounding mode HALF_EVEN Examples</b></caption>*<tr valign=top><th>Input Number</th>*    <th>Input rounded to one digit<br> with {@code HALF_EVEN} rounding*<tr align=right><td>5.5</td>  <td>6</td>*<tr align=right><td>2.5</td>  <td>2</td>*<tr align=right><td>1.6</td>  <td>2</td>*<tr align=right><td>1.1</td>  <td>1</td>*<tr align=right><td>1.0</td>  <td>1</td>*<tr align=right><td>-1.0</td> <td>-1</td>*<tr align=right><td>-1.1</td> <td>-1</td>*<tr align=right><td>-1.6</td> <td>-2</td>*<tr align=right><td>-2.5</td> <td>-2</td>*<tr align=right><td>-5.5</td> <td>-6</td>*</table>*/HALF_EVEN(BigDecimal.ROUND_HALF_EVEN),/*** Rounding mode to assert that the requested operation has an exact* result, hence no rounding is necessary.  If this rounding mode is* specified on an operation that yields an inexact result, an* {@code ArithmeticException} is thrown.*<p>Example:*<table border>* <caption><b>Rounding mode UNNECESSARY Examples</b></caption>*<tr valign=top><th>Input Number</th>*    <th>Input rounded to one digit<br> with {@code UNNECESSARY} rounding*<tr align=right><td>5.5</td>  <td>throw {@code ArithmeticException}</td>*<tr align=right><td>2.5</td>  <td>throw {@code ArithmeticException}</td>*<tr align=right><td>1.6</td>  <td>throw {@code ArithmeticException}</td>*<tr align=right><td>1.1</td>  <td>throw {@code ArithmeticException}</td>*<tr align=right><td>1.0</td>  <td>1</td>*<tr align=right><td>-1.0</td> <td>-1</td>*<tr align=right><td>-1.1</td> <td>throw {@code ArithmeticException}</td>*<tr align=right><td>-1.6</td> <td>throw {@code ArithmeticException}</td>*<tr align=right><td>-2.5</td> <td>throw {@code ArithmeticException}</td>*<tr align=right><td>-5.5</td> <td>throw {@code ArithmeticException}</td>*</table>*/UNNECESSARY(BigDecimal.ROUND_UNNECESSARY);// Corresponding BigDecimal rounding constantfinal int oldMode;/*** Constructor** @param oldMode The {@code BigDecimal} constant corresponding to*        this mode*/private RoundingMode(int oldMode) {this.oldMode = oldMode;}/*** Returns the {@code RoundingMode} object corresponding to a* legacy integer rounding mode constant in {@link BigDecimal}.** @param  rm legacy integer rounding mode to convert* @return {@code RoundingMode} corresponding to the given integer.* @throws IllegalArgumentException integer is out of range*/public static RoundingMode valueOf(int rm) {switch(rm) {case BigDecimal.ROUND_UP:return UP;case BigDecimal.ROUND_DOWN:return DOWN;case BigDecimal.ROUND_CEILING:return CEILING;case BigDecimal.ROUND_FLOOR:return FLOOR;case BigDecimal.ROUND_HALF_UP:return HALF_UP;case BigDecimal.ROUND_HALF_DOWN:return HALF_DOWN;case BigDecimal.ROUND_HALF_EVEN:return HALF_EVEN;case BigDecimal.ROUND_UNNECESSARY:return UNNECESSARY;default:throw new IllegalArgumentException("argument out of range");}}
}

8种舍位模式含义解析:

  • RoundingMode.UP:正数向上舍位,负数向下舍位。
  • RoundingMode.DOWN:直接保留指定位数数字,可以理解为截取。
  • RoundingMode.CEILING:直译是天花板的意思,正数的效果如同 RoundingMode.UP,负数的效果如同 RoundingMode.DOWN。
  • RoundingMode.FLOOR:直译是地板的意思,和 RoundingMode.CEILING 刚好相反,正数的效果如同 RoundingMode.DOWN,负数的效果如同 RoundingMode.UP。
  • RoundingMode.HALF_UP:就是比较常见的四舍五入。
  • RoundingMode.HALF_DOWN:五舍六入。
  • RoundingMode.HALF_EVEN:指定位数后面的小数是5,且5后面有数字且这些数字不全部为0,则进一位,否则看5前面的一位,如果是奇数就进一位,如果是偶数则不进位,其他情况四舍五入。
  • RoundingMode.UNNECESSARY:指定位数后没有数字或者全部是0,否则会抛出异常。

RoundingMode.UP 验证:

BigDecimal bigDecimal1 = new BigDecimal("1.235");
BigDecimal up1 = bigDecimal1.setScale(2, RoundingMode.UP);
BigDecimal bigDecimal2 = new BigDecimal("-1.233");
BigDecimal up2 = bigDecimal2.setScale(2, RoundingMode.UP);
System.out.println("up1:" + up1);
System.out.println("up2:" + up2);

执行结果:

up1:1.24
up2:-1.24

正数向上舍位,负数向下舍位,符合预期。

RoundingMode.HALF_DOWN 验证:

BigDecimal down = new BigDecimal("1.235").setScale(2, RoundingMode.DOWN);
System.out.println("down:" + down);

执行结果:

down:1.23

截取直接保留指定位数数字,符合预期。

RoundingMode.CEILING 验证:

BigDecimal ceilingOne = new BigDecimal("1.235").setScale(2, RoundingMode.CEILING);
BigDecimal ceilingTwo = new BigDecimal("-1.235").setScale(2, RoundingMode.CEILING);
System.out.println("ceilingOne:" + ceilingOne);
System.out.println("ceilingTwo:" + ceilingTwo);

执行结果:

ceilingOne:1.24
ceilingTwo:-1.23

正数向上舍位,负数直接截取,符合预期。

RoundingMode.FLOOR 验证:

BigDecimal floorOne = new BigDecimal("1.235").setScale(2, RoundingMode.FLOOR);
BigDecimal floorTwo = new BigDecimal("-1.235").setScale(2, RoundingMode.FLOOR);
System.out.println("floorOne:" + floorOne);
System.out.println("floorTwo:" + floorTwo);

执行结果:

floorOne:1.23
floorTwo:-1.24

正数截取,负数向下舍位,符合预期。

RoundingMode.HALF_UP 验证:

BigDecimal halfUpOne = new BigDecimal("1.235").setScale(2, RoundingMode.HALF_UP);
BigDecimal halfUpTwo = new BigDecimal("1.234").setScale(2, RoundingMode.HALF_UP);
System.out.println("halfUpOne:" + halfUpOne);
System.out.println("halfUpTwo:" + halfUpTwo);

执行结果:

halfUpOne:1.24
halfUpTwo:1.23

四舍五入,符合预期。

RoundingMode.HALF_EVEN 验证:

BigDecimal halfEvenOne = new BigDecimal("1.2351").setScale(2, RoundingMode.HALF_EVEN);
BigDecimal halfEvenTwo = new BigDecimal("1.2250").setScale(2, RoundingMode.HALF_EVEN);
BigDecimal halfEvenThree = new BigDecimal("1.2350").setScale(2, RoundingMode.HALF_EVEN);
BigDecimal halfEvenFour = new BigDecimal("1.2450").setScale(2, RoundingMode.HALF_EVEN);
BigDecimal halfEvenFive = new BigDecimal("1.244").setScale(2, RoundingMode.HALF_EVEN);
BigDecimal halfEvenSix = new BigDecimal("1.246").setScale(2, RoundingMode.HALF_EVEN);
System.out.println("halfEvenOne:" + halfEvenOne);
System.out.println("halfEvenTwo:" + halfEvenTwo);
System.out.println("halfEvenThree:" + halfEvenThree);
System.out.println("halfEvenFour:" + halfEvenFour);
System.out.println("halfEvenFive:" + halfEvenFive);
System.out.println("halfEvenSix:" + halfEvenSix);

执行结果:

halfEvenOne:1.24
halfEvenTwo:1.22
halfEvenThree:1.24
halfEvenFour:1.24
halfEvenFive:1.24
halfEvenSix:1.25

符合预期。

RoundingMode.HALF_EVEN 验证:

BigDecimal unnecessaryOne = new BigDecimal("1.240").setScale(2, RoundingMode.UNNECESSARY);
System.out.println("unnecessaryOne:" + unnecessaryOne);
BigDecimal unnecessaryTwo = new BigDecimal("1.2401").setScale(2, RoundingMode.UNNECESSARY);
System.out.println("unnecessaryTwo:" + unnecessaryTwo);

执行结果:

unnecessaryOne:1.24
Exception in thread "main" java.lang.ArithmeticException: Rounding necessaryat java.math.BigDecimal.commonNeedIncrement(BigDecimal.java:4148)at java.math.BigDecimal.needIncrement(BigDecimal.java:4204)at java.math.BigDecimal.divideAndRound(BigDecimal.java:4112)at java.math.BigDecimal.setScale(BigDecimal.java:2452)at java.math.BigDecimal.setScale(BigDecimal.java:2386)at com.zt.dc.portal.admin.web.service.impl.satisfaction.SatisfactionEvaluationServiceImpl.main(SatisfactionEvaluationServiceImpl.java:262)

一个正常输出,一个抛出异常,符合预期。

总结:本文对 RoundingMode 共有 8 种舍位方式进行了详细分析验证,希望可以帮助到有需要的小伙伴。

欢迎提出建议及对错误的地方指出纠正。

这篇关于BigDecimal 小数位的处理(RoundingMode)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1089065

相关文章

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

Springboot处理跨域的实现方式(附Demo)

《Springboot处理跨域的实现方式(附Demo)》:本文主要介绍Springboot处理跨域的实现方式(附Demo),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录Springboot处理跨域的方式1. 基本知识2. @CrossOrigin3. 全局跨域设置4.

python+opencv处理颜色之将目标颜色转换实例代码

《python+opencv处理颜色之将目标颜色转换实例代码》OpenCV是一个的跨平台计算机视觉库,可以运行在Linux、Windows和MacOS操作系统上,:本文主要介绍python+ope... 目录下面是代码+ 效果 + 解释转HSV: 关于颜色总是要转HSV的掩膜再标注总结 目标:将红色的部分滤

Python实现自动化接收与处理手机验证码

《Python实现自动化接收与处理手机验证码》在移动互联网时代,短信验证码已成为身份验证、账号注册等环节的重要安全手段,本文将介绍如何利用Python实现验证码的自动接收,识别与转发,需要的可以参考下... 目录引言一、准备工作1.1 硬件与软件需求1.2 环境配置二、核心功能实现2.1 短信监听与获取2.

Python使用date模块进行日期处理的终极指南

《Python使用date模块进行日期处理的终极指南》在处理与时间相关的数据时,Python的date模块是开发者最趁手的工具之一,本文将用通俗的语言,结合真实案例,带您掌握date模块的六大核心功能... 目录引言一、date模块的核心功能1.1 日期表示1.2 日期计算1.3 日期比较二、六大常用方法详

利用Go语言开发文件操作工具轻松处理所有文件

《利用Go语言开发文件操作工具轻松处理所有文件》在后端开发中,文件操作是一个非常常见但又容易出错的场景,本文小编要向大家介绍一个强大的Go语言文件操作工具库,它能帮你轻松处理各种文件操作场景... 目录为什么需要这个工具?核心功能详解1. 文件/目录存javascript在性检查2. 批量创建目录3. 文件

Java使用多线程处理未知任务数的方案介绍

《Java使用多线程处理未知任务数的方案介绍》这篇文章主要为大家详细介绍了Java如何使用多线程实现处理未知任务数,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 知道任务个数,你可以定义好线程数规则,生成线程数去跑代码说明:1.虚拟线程池:使用 Executors.newVir

一文带你深入了解Python中的GeneratorExit异常处理

《一文带你深入了解Python中的GeneratorExit异常处理》GeneratorExit是Python内置的异常,当生成器或协程被强制关闭时,Python解释器会向其发送这个异常,下面我们来看... 目录GeneratorExit:协程世界的死亡通知书什么是GeneratorExit实际中的问题案例

最新Spring Security实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)

《最新SpringSecurity实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)》本章节介绍了如何通过SpringSecurity实现从配置自定义登录页面、表单登录处理逻辑的配置,并简单模拟... 目录前言改造准备开始登录页改造自定义用户名密码登陆成功失败跳转问题自定义登出前后端分离适配方案结语前言