1. BigDecimal类概述:
由于在运算的时候,float类型和double很容易丢失精度。所以为了能够精确的表达、计算浮点数,Java提供了BigDecimal。
BigDecimal:不可变、任意精度的有符号十进制数。
2. BigDecimal构造方法
1 public BigDecimal(String val)
3. BigDecimal的使用(加减乘除)
1 public BigDecimal add(BigDecimal augend):加 2 public BigDecimal subtract(BigDecimal subtrahend):减 3 public BigDecimal multiply(BigDecimal divisor):乘 4 public BigDecimal divide(BigDecimal divisor):除 5 public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode):商,几位小数(scale),如何舍取(roundingMode)
代码演示:
1 package cn.itcast_02; 2 3 import java.math.BigDecimal; 4 5 /* 6 * 构造方法: 7 * public BigDecimal(String val) 8 * 9 * public BigDecimal add(BigDecimal augend) 10 * public BigDecimal subtract(BigDecimal subtrahend) 11 * public BigDecimal multiply(BigDecimal multiplicand) 12 * public BigDecimal divide(BigDecimal divisor) 13 * public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode):商,几位小数,如何舍取 14 */ 15 public class BigDecimalDemo { 16 public static void main(String[] args) { 17 // System.out.println(0.09 + 0.01); 18 // System.out.println(1.0 - 0.32); 19 // System.out.println(1.015 * 100); 20 // System.out.println(1.301 / 100); 21 22 BigDecimal bd1 = new BigDecimal("0.09"); 23 BigDecimal bd2 = new BigDecimal("0.01"); 24 System.out.println("add:" + bd1.add(bd2)); 25 System.out.println("-------------------"); 26 27 BigDecimal bd3 = new BigDecimal("1.0"); 28 BigDecimal bd4 = new BigDecimal("0.32"); 29 System.out.println("subtract:" + bd3.subtract(bd4)); 30 System.out.println("-------------------"); 31 32 BigDecimal bd5 = new BigDecimal("1.015"); 33 BigDecimal bd6 = new BigDecimal("100"); 34 System.out.println("multiply:" + bd5.multiply(bd6)); 35 System.out.println("-------------------"); 36 37 BigDecimal bd7 = new BigDecimal("1.301"); 38 BigDecimal bd8 = new BigDecimal("100"); 39 System.out.println("divide:" + bd7.divide(bd8)); 40 System.out.println("divide:" 41 + bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP)); 42 System.out.println("divide:" 43 + bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP)); 44 } 45 }
运行效果:
时间: 2024-10-11 22:54:53