比较 BigDecimals
方法 compareTo 用于比较 BigDecimals:
BigDecimal a = new BigDecimal(5); a.compareTo(new BigDecimal(0)); //a is greater, returns 1 a.compareTo(new BigDecimal(5)); //a is equal, returns 0 a.compareTo(new BigDecimal(10)); //a is less, returns -1
通常你不应该使用 equals 方法,因为它认为两个 BigDecimals 只有在它们的值和比例相等时才相等:
BigDecimal a = new BigDecimal(5); a.equals(new BigDecimal(5)); //value and scale are equal, returns true a.equals(new BigDecimal(5.00)); //value is equal but scale is not, returns false
使用 BigDecimal 而不是浮点数
由于浮点类型在计算机内存中的表示方式,使用这种类型的运算结果可能不准确,某些值存储为近似值。
货币计算就是很好的例子。
如果需要高精度,则应使用其他类型。
例如Java 7 提供了 BigDecimal。
import java.math.BigDecimal; public class FloatTest { public static void main(String[] args) { float accountBalance = 10000.00f; System.out.println("Operations using float:"); System.out.println("1000 operations for 1.99"); for(int i = 0; i<1000; i++){ accountBalance -= 1.99f; } System.out.println(String.format("Account balance after float operations: %f", accountBalance)); BigDecimal accountBalanceTwo = new BigDecimal("10000.00"); System.out.println("Operations using BigDecimal:"); System.out.println("1000 operations for 1.99"); BigDecimal operation = new BigDecimal("1.99"); for(int i = 0; i<1000; i++){ accountBalanceTwo = accountBalanceTwo.subtract(operation); } System.out.println(String.format("Account balance after BigDecimal operations: %f", accountBalanceTwo)); }
这个程序的输出是:
Operations using float: 1000 operations for 1.99 Account balance after float operations: 8009,765625 Operations using BigDecimal: 1000 operations for 1.99 Account balance after BigDecimal operations: 8010,000000
对于 10000.00 的起始余额,在 1.99 的 1000 次操作后,我们预计余额为 8010.00。
使用 float 类型为我们提供了大约 8009.77 的答案,这在货币计算的情况下是不可接受的不精确。
使用 BigDecimal 为我们提供了正确的结果。
BigDecimal.valueOf()
BigDecimal 类包含常用数字的内部缓存,例如0 到 10.
提供 BigDecimal.valueOf() 方法优先于具有相似类型参数的构造函数,例如:在下面的示例中,a 优先于 b。
BigDecimal a = BigDecimal.valueOf(10L); //Returns cached Object reference BigDecimal b = new BigDecimal(10L); //Does not return cached Object reference BigDecimal a = BigDecimal.valueOf(20L); //Does not return cached Object reference BigDecimal b = new BigDecimal(20L); //Does not return cached Object reference BigDecimal a = BigDecimal.valueOf(15.15); //Preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting from constructing a BigDecimal from the result of using Double.toString(double) BigDecimal b = new BigDecimal(15.15); //Return unpredictable result
Java 类中的 BigDecimal 提供算术运算(加、减、乘、除)、缩放操作、舍入、比较、散列和格式转换。
BigDecimal 表示不可变的、任意精度的有符号十进制数。
该类用于高精度计算的需要。
日期:2020-06-02 22:15:15 来源:oir作者:oir