增加BigDecimal

我想用一些BigDecimaltypes的货币值做一些简单的总和。

 BigDecimal test = new BigDecimal(0); System.out.println(test); test.add(new BigDecimal(30)); System.out.println(test); test.add(new BigDecimal(45)); System.out.println(test); 

显然我不太了解BigDecimalalgorithm,看后面的输出。

 Test 0 0 0 

谁能帮我吗?

BigDecimal是不可变的,所以你需要这样做:

 BigDecimal result = test.add(new BigDecimal(30)); System.out.println(result); 

它看起来像从这里的Java文档添加返回一个新的BigDecimal:

 BigDecimal test = new BigDecimal(0); System.out.println(test); test = test.add(new BigDecimal(30)); System.out.println(test); test = test.add(new BigDecimal(45)); System.out.println(test); 
 BigDecimal test = new BigDecimal(0); System.out.println(test); test = test.add(new BigDecimal(30)); System.out.println(test); test = test.add(new BigDecimal(45)); System.out.println(test); 

其实很简单 只要这样做:

 BigDecimal test = new BigDecimal(0); System.out.println(test); test = test.add(new BigDecimal(30)); System.out.println(test); test = test.add(new BigDecimal(45)); System.out.println(test); 

另请参阅: BigDecimal#add(java.math.BigDecimal)

BigInteger是不可变的,你需要这样做,

  BigInteger sum = test.add(new BigInteger(30)); System.out.println(sum); 
 //you can do in this way...as BigDecimal is immutable so cant set values except in constructor BigDecimal test = BigDecimal.ZERO; BigDecimal result = test.add(new BigDecimal(30)); System.out.println(result); result would be 30 
 BigDecimal no = new BigDecimal(10); //you can add like this also no = no.add(new BigDecimal(10)); System.out.println(no); 

20

 BigDecimal demo = new BigDecimal(15); 

它是不可变的,因为它内部存储你input即(15)作为final private final BigInteger intVal; 并且在创buildstring的时候使用相同的概念,每个input都最终在private final char value[]; 所以不存在缺陷。

只是添加BigDecimals另一个例子。 关键在于它们是不可变的,只能在构造函数中初始化它们。 这里是代码:

 import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { Scanner sc; boolean first_right_number = false; BigDecimal initBigDecimal = BigDecimal.ZERO; BigDecimal add1 = BigDecimal.ZERO; BigDecimal add2 = BigDecimal.ZERO; while (!first_right_number) { System.out.print("Enter a first single numeric value: "); sc = new Scanner(System.in); if (sc.hasNextBigDecimal()) { first_right_number = true; add1 = sc.nextBigDecimal(); } } boolean second_right_number = false; while (!second_right_number) { System.out.print("Enter a second single numeric value: "); sc = new Scanner(System.in); if (sc.hasNextBigDecimal()) { second_right_number = true; add2 = sc.nextBigDecimal(); } } BigDecimal result = initBigDecimal.add(add1).add(add2); System.out.println("Sum of the 2 numbers is: " + result.toString()); } }