曹耘豪的博客

Java里数字的比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
assert 1.00f == 1.000f;
assert 1.00d == 1.000f;
assert 1.00d == 1.000d;
assert new Float("1.00").equals(new Float("1.000"));
assert new Double("1.00").equals(new Double("1.000"));
assert !new Double("1.00").equals(new Float("1.00"));

assert new BigDecimal("1.00").equals(new BigDecimal("1.00"));
assert !new BigDecimal("1.00").equals(new BigDecimal("1.000")); // 比较精度
assert new BigDecimal("1.00").compareTo(new BigDecimal("1.000")) == 0; // 不比较精度

assert new BigDecimal("0").signum() == 0;
assert new BigDecimal("0.00").signum() == 0;
assert new BigDecimal("-0.00").signum() == 0;

assert String.valueOf(Double.POSITIVE_INFINITY).equals("Infinity");
assert String.valueOf(Double.NEGATIVE_INFINITY).equals("-Infinity");
assert Double.parseDouble("Infinity") == Double.POSITIVE_INFINITY;

assert String.valueOf(Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY).equals("NaN");
assert Double.parseDouble("NaN") != Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY;
assert Double.valueOf("NaN").equals(Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY);

assert 0.0d != Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY;
assert !Double.valueOf(0.0d).equals(Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY);
   /