注意假设结果是无限位小数,不指定位数进行四舍五入的话会报错
import java.util.Scanner; import java.math.BigDecimal; public class Main { public static void main(String args[]){ Scanner in = new Scanner(System.in); BigDecimal a = in.nextBigDecimal(); BigDecimal b = in.nextBigDecimal(); System.out.println("Add " + a.add(b)); System.out.println("Sub " + a.subtract(b)); System.out.println("Mul " + a.multiply(b)); System.out.println("divide " + a.divide(b));//此处假设结果是无限循环。就会报错 System.out.println("四舍五入: " + a.divide(b,5,BigDecimal.ROUND_HALF_UP)); //第二个參数是小数位数 a.divide(b,5,BigDecimal.ROUND_HALF_UP).doubleValue; double d1 = 3.1415926; BigDecimal t1 = new BigDecimal(d1); //依次能够进行doubleToBigDecimal的转换 int d2 = 3214856; BigDecimal t2 = new BigDecimal(d2); BigDecimal t3 = new BigDecimal("843269136"); System.out.println("dobule TO : " + t1); System.out.println("Int to : " + t2); System.out.println("String to : " + t3); } }