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自动化处理PDF文档的操作完整指南

《Python自动化处理PDF文档的操作完整指南》在办公自动化中,PDF文档处理是一项常见需求,本文将介绍如何使用Python实现PDF文档的自动化处理,感兴趣的小伙伴可以跟随小编一起学习一下... 目录使用pymupdf读写PDF文件基本概念安装pymupdf提取文本内容提取图像添加水印使用pdfplum

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

基于Redis自动过期的流处理暂停机制

《基于Redis自动过期的流处理暂停机制》基于Redis自动过期的流处理暂停机制是一种高效、可靠且易于实现的解决方案,防止延时过大的数据影响实时处理自动恢复处理,以避免积压的数据影响实时性,下面就来详... 目录核心思路代码实现1. 初始化Redis连接和键前缀2. 接收数据时检查暂停状态3. 检测到延时过

Java利用@SneakyThrows注解提升异常处理效率详解

《Java利用@SneakyThrows注解提升异常处理效率详解》这篇文章将深度剖析@SneakyThrows的原理,用法,适用场景以及隐藏的陷阱,看看它如何让Java异常处理效率飙升50%,感兴趣的... 目录前言一、检查型异常的“诅咒”:为什么Java开发者讨厌它1.1 检查型异常的痛点1.2 为什么说

Python利用PySpark和Kafka实现流处理引擎构建指南

《Python利用PySpark和Kafka实现流处理引擎构建指南》本文将深入解剖基于Python的实时处理黄金组合:Kafka(分布式消息队列)与PySpark(分布式计算引擎)的化学反应,并构建一... 目录引言:数据洪流时代的生存法则第一章 Kafka:数据世界的中央神经系统消息引擎核心设计哲学高吞吐

Go语言使用Gin处理路由参数和查询参数

《Go语言使用Gin处理路由参数和查询参数》在WebAPI开发中,处理路由参数(PathParameter)和查询参数(QueryParameter)是非常常见的需求,下面我们就来看看Go语言... 目录一、路由参数 vs 查询参数二、Gin 获取路由参数和查询参数三、示例代码四、运行与测试1. 测试编程路

Java异常捕获及处理方式详解

《Java异常捕获及处理方式详解》异常处理是Java编程中非常重要的一部分,它允许我们在程序运行时捕获并处理错误或不预期的行为,而不是让程序直接崩溃,本文将介绍Java中如何捕获异常,以及常用的异常处... 目录前言什么是异常?Java异常的基本语法解释:1. 捕获异常并处理示例1:捕获并处理单个异常解释:

MyBatis的xml中字符串类型判空与非字符串类型判空处理方式(最新整理)

《MyBatis的xml中字符串类型判空与非字符串类型判空处理方式(最新整理)》本文给大家介绍MyBatis的xml中字符串类型判空与非字符串类型判空处理方式,本文给大家介绍的非常详细,对大家的学习或... 目录完整 Hutool 写法版本对比优化为什么status变成Long?为什么 price 没事?怎

MySQL中处理数据的并发一致性的实现示例

《MySQL中处理数据的并发一致性的实现示例》在MySQL中处理数据的并发一致性是确保多个用户或应用程序同时访问和修改数据库时,不会导致数据冲突、数据丢失或数据不一致,MySQL通过事务和锁机制来管理... 目录一、事务(Transactions)1. 事务控制语句二、锁(Locks)1. 锁类型2. 锁粒

Python调用LibreOffice处理自动化文档的完整指南

《Python调用LibreOffice处理自动化文档的完整指南》在数字化转型的浪潮中,文档处理自动化已成为提升效率的关键,LibreOffice作为开源办公软件的佼佼者,其命令行功能结合Python... 目录引言一、环境搭建:三步构建自动化基石1. 安装LibreOffice与python2. 验证安装