首页 > 其他分享 >BigDecimal

BigDecimal

时间:2024-03-27 17:03:36浏览次数:17  
标签:舍入 Rounded BigDecimal places decimal RoundingMode

概述

Immutable, arbitrary-precision signed decimal numbers.  不可变的、任意精度的 有符号的 十进制数
A {@code BigDecimal} consists of an arbitrary precision integer <i>unscaled value</i> and a 32-bit integer <i>scale</i>.  
If zero or positive, the scale is the number of digits to the right of the decimal point.
If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.
The value of the number represented by the {@code BigDecimal} is therefore <tt>(unscaledValue &times; 10<sup>-scale</sup>)</tt>.

 

The {@code BigDecimal} class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.
The {@link #toString} method provides a canonical representation of a {@code BigDecimal}.

BigDecimal 提供了 算术运算、四舍五入、比较、哈希、格式转换 等操作;

 

The {@code BigDecimal} class gives its user complete control over rounding behavior.
If no rounding mode is specified and the exact result cannot be represented, an exception is thrown; otherwise, calculations can be carried out to a chosen precision and rounding mode by supplying an appropriate {@link MathContext} object to the operation.

BigDecimal 提供 四舍五入 的操作;

如果 没有设置四舍五入的模式,则无法表示精确的结果,将会抛出异常;
In either case, eight <em>rounding modes</em> are provided for the control of rounding.
Using the integer fields in this class (such as {@link #ROUND_HALF_UP}) to represent rounding mode is largely obsolete; the enumeration values of the {@code RoundingMode} {@code enum}, (such as {@link RoundingMode#HALF_UP}) should be used instead.

提供了8种四舍五入模式:

使用 该类的 RoundingMode#HALF_UP 设置 模式;

...

 

 

 

常用函数

构造方法

  1. BigDecimal(double val)
    • 使用 double 类型的值构造 BigDecimal
    • 注意:由于 double 类型的精度问题,使用此构造方法可能会导致精度损失。
  2. BigDecimal(String val)
    • 使用 String 类型的值构造 BigDecimal
    • 这是推荐的构造方法,因为它可以避免 double 类型的精度问题。

算术运算

  1. add(BigDecimal augend)
    • 加法。
  2. subtract(BigDecimal subtrahend)
    • 减法。
  3. multiply(BigDecimal multiplicand)
    • 乘法。
  4. divide(BigDecimal divisor, int scale, int roundingMode)
    • 除法,并指定结果的小数位数和舍入模式。
  5. divide(BigDecimal divisor, RoundingMode roundingMode)
    • 除法,并指定舍入模式。
  6. pow(int n)
    • 求幂。
  7. negate()
    • 取反。
  8. abs()
    • 取绝对值。

标度操作

  1. setScale(int newScale, RoundingMode roundingMode)
    • 设置标度(小数点后的位数),并指定舍入模式。
  2. setScale(int newScale, int roundingMode)
    • 设置标度,并指定旧的舍入模式常量(现已过时,建议使用 RoundingMode)。
  3. setScale(int newScale)
    • 设置标度,使用默认的舍入模式(RoundingMode.HALF_UP)。

示例  

import java.math.BigDecimal;  
import java.math.RoundingMode;  
  
public class BigDecimalScaleExample {  
    public static void main(String[] args) {  
        // 创建一个 BigDecimal 对象  
        BigDecimal bigDecimal = new BigDecimal("123.456789");  
  
        // 设置标度为 2,使用四舍五入模式  
        BigDecimal rounded = bigDecimal.setScale(2, RoundingMode.HALF_UP);  
        System.out.println("Rounded to 2 decimal places: " + rounded); // 输出: Rounded to 2 decimal places: 123.46  
  
        // 设置标度为 4,使用向下舍入模式  
        BigDecimal truncated = bigDecimal.setScale(4, RoundingMode.DOWN);  
        System.out.println("Truncated to 4 decimal places: " + truncated); // 输出: Truncated to 4 decimal places: 123.4567  
  
        // 设置标度为 0,使用向零舍入模式  
        BigDecimal roundedToZero = bigDecimal.setScale(0, RoundingMode.TOWARDS_ZERO);  
        System.out.println("Rounded to 0 decimal places towards zero: " + roundedToZero); // 输出: Rounded to 0 decimal places towards zero: 123  
  
        // 设置标度为 2,使用向上舍入模式  
        BigDecimal roundedUp = bigDecimal.setScale(2, RoundingMode.UP);  
        System.out.println("Rounded to 2 decimal places up: " + roundedUp); // 输出: Rounded to 2 decimal places up: 123.46  
  
        // 设置标度为 3,使用向正无穷大舍入模式  
        BigDecimal roundedCeiling = bigDecimal.setScale(3, RoundingMode.CEILING);  
        System.out.println("Rounded to 3 decimal places ceiling: " + roundedCeiling); // 输出: Rounded to 3 decimal places ceiling: 123.457  
  
        // 设置标度为 3,使用向负无穷大舍入模式  
        BigDecimal roundedFloor = new BigDecimal("-123.456789").setScale(3, RoundingMode.FLOOR);  
        System.out.println("Rounded to 3 decimal places floor: " + roundedFloor); // 输出: Rounded to 3 decimal places floor: -123.457  
    }  
}

  

比较

  1. compareTo(BigDecimal val)
    • 比较两个 BigDecimal 对象的大小。
  2. equals(Object x)
    • 判断两个 BigDecimal 对象是否相等。

舍入

  1. round(MathContext mc)
    • 根据指定的 MathContext 进行舍入。
  2. round(RoundingMode roundingMode)
    • 根据指定的舍入模式进行舍入。

格式化

  1. toPlainString()
    • 将 BigDecimal 转换为不包含科学记数法的字符串。
  2. toString()
    • 将 BigDecimal 转换为字符串,可能使用科学记数法。
  3. stripTrailingZeros()
    • 返回一个新的 BigDecimal,它是通过移除此 BigDecimal 的任何尾随零得到的。

其他

  1. doubleValue()
    • 将 BigDecimal 转换为 double(可能导致精度损失)。
  2. floatValue()
    • 将 BigDecimal 转换为 float(可能导致精度损失)。
  3. longValue()
    • 将 BigDecimal 转换为 long(如果值太大或太小,则抛出异常)。
  4. intValue()
    • 将 BigDecimal 转换为 int(如果值太大或太小,则抛出异常)。
  5. hashCode()
    • 返回 BigDecimal 的哈希码。

 

标签:舍入,Rounded,BigDecimal,places,decimal,RoundingMode
From: https://www.cnblogs.com/anpeiyong/p/18099721

相关文章

  • BigDecimal
    3.BigDecimal3.1介绍BigDecimal是Java在java.math包中提供的线程安全的API类。用于解决小数运算中,出现的不精确问题3.2创建对象BigDecimal所创建的是对象,故我们不能使用传统的+、-、*、/等算术运算符直接对其对象进行数学运算,而必须调用其相对应的方法。方法中的参数也必须......
  • BigDecimal值在java比较的两种方法
    1、使用equals()方法不但要求两个BigDecimal的值相等,还要求它们的scale()相等。BigDecimald1=newBigDecimal("123.45");BigDecimald2=newBigDecimal("123.45000");System.out.println(d1.equals(d2));//false,因为scale不同System.out.println(d1.equa......
  • BigDecimal 除不尽导致下单 异常
    publicstaticvoidmain(String[]args){//异常代码,除不尽导致//BigDecimaldivide=newBigDecimal(1).divide(newBigDecimal(0.3));/*Exceptioninthread"main"java.lang.ArithmeticException:Non-terminatingdecim......
  • BigDecimal的基本使用
    BigDecimal的基本使用BigDecimal是Java中用于处理高精度数值的类。它可以表示任意精度的小数,并提供了各种数值运算的方法。1、创建BigDecimal对象BigDecimal类提供了多个方法来创建BigDecimal对象,下面是一些常用的方法: -BigDecimal(Stringval):使用字符串作为参数创建Bi......
  • BigDecimalSerializer
    @JsonSerialize(using=BigDecimalSerializer.class)publicclassBigDecimalSerializerextendsJsonSerializer{@Overridepublicvoidserialize(BigDecimalvalue,JsonGeneratorgen,SerializerProviderserializers)throwsIOException,JsonProcessingException......
  • BigDecimal的基本使用
    BigDecimal的基本使用BigDecimal是Java中用于处理高精度数值的类。它可以表示任意精度的小数,并提供了各种数值运算的方法。1、创建BigDecimal对象BigDecimal类提供了多个方法来创建BigDecimal对象,下面是一些常用的方法: -BigDecimal(Stringval):使用字符串作为参数创建Bi......
  • 原来你是这样的JAVA--[07]聊聊Integer和BigDecimal
    今天来聊聊Java中跟数值处理相关的两个类型Integer和BigDecimal。说起这两个类型,我们肯定都不陌生,但是其中有些容易踩到的坑需要注意避让。Integer整型我们应该每天都会用到,但是每种语言还是有自己的特性。从敬姐刚从.NET转过来的时候踩过的一个坑说起:话说在.NET世界中,数值的基......
  • 从BigDecimal的divide的异常说起
    在过去做项目的某一天中,突然有小伙伴说两个BigDecimal的数据相除(divide)报错了,觉得不可能,然后问他是怎么编写的,他说很简单呀,就是new了2个BigDecimal,然后相除的结果赋值给另外一个BigDecimal对象。听起来觉得没有问题,正常来说,2个Integer(int),2个Double(double)都不会报错,然后问是什么......
  • JAVA之BigDecimal详解
    一、BigDecimal概述Java在java.math包中提供的API类BigDecimal,用来对超过16位有效位的数进行精确的运算。双精度浮点型变量double可以处理16位有效数,但在实际应用中,可能需要对更大或者更小的数进行运算和处理。一般情况下,对于那些不需要准确计算精度的数字,我们可以直接使用Float......
  • Bigdecimal四则运算怎么减少精度损失
    在进行BigDecimal的四则运算时,通常建议将除法运算放在最后进行,以减小精度损失。这是因为在除法运算中,小数位数可能会增加,导致结果的精度减小。具体来说,如果你按照以下顺序进行四则运算,可以最大程度地保持精度:加法和减法:可以按照需要进行加法和减法运算,这不太会影响精度。乘......