1. 构造函数的坑
|
|
输出结果:
可以看到,直接使用double作为参数构造BigDecimal时,会丢失精度。
所以推荐的是先将double转化为字符串,然后赋值给构造函数。
2. 数值计算丢失精度
|
|
输出结果:
尝试调用floatValue()
方法获取浮点值时,内部其实会将double转化为float,导致精度丢失。
所以要求使用BigDecimal提供的计算方法做四则运算,最后将结果返回指定数值类型。
3. 四舍五入
3.1 ROUND_UP
Rounding mode to round away from zero. Always increments the digit prior to a nonzero discarded fraction.
不关心正负的无脑向上取整,远离0。
|
|
输出结果:
3.2 ROUND_DOWN
Rounding mode to round towards zero. Never increments the digit prior to a discarded fraction (i.e., truncates).
不关心正负的无脑向下取整,靠近0。
|
|
输出结果:
3.3 ROUND_CEILING
Rounding mode to round towards positive infinity. If the BigDecimal is positive, behaves as for ROUND_UP; if negative, behaves as for ROUND_DOWN.
向正无穷取整,如果是正值,那么表现跟ROUND_UP一样,如果是负值,那么表现跟ROUND_DOWN一样。
|
|
输出结果:
3.4 ROUND_FLOOR
Rounding mode to round towards negative infinity. If the BigDecimal is positive, behave as for ROUND_DOWN; if negative, behave as for ROUND_UP.
向负无穷取整,如果是正值,那么表现跟ROUND_DOWN一样,如果是负值,那么表现跟ROUND_UP一样。
|
|
输出结果:
3.5 ROUND_HALF_UP
Rounding mode to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for ROUND_DOWN.
不关心正负的无脑四舍五入,如果是5,那么进位。
|
|
输出结果:
3.6 ROUND_HALF_DOWN
Rounding mode to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round down. Behaves as for ROUND_UP if the discarded fraction is > 0.5; otherwise, behaves as for ROUND_DOWN.
不关心正负的无脑四舍五入,如果是5,那么舍掉。
|
|
输出结果:
3.7 ROUND_HALF_EVEN
Rounding mode to round towards the “nearest neighbor” unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it’s even.
不关心正负的无脑四舍五入,如果是5,那么看左边数字奇偶性,如果左边数字是奇数,那么进位,如果是偶数,那么舍掉。
|
|
输出结果: