交易系统中,因为精度问题,交易数值建议使用BigDecimal类型。
public static void main(String[] args) {
double a = 24.93;
System.out.println(BigDecimal.valueOf(a));
System.out.println(new BigDecimal(a));
System.out.println(new BigDecimal(String.valueOf(a)));
double value = 1.111;
System.out.println(new BigDecimal(value).setScale(1,BigDecimal.ROUND_DOWN));
System.out.println(new BigDecimal(value).setScale(2,BigDecimal.ROUND_DOWN));
System.out.println(new BigDecimal(value).setScale(3,BigDecimal.ROUND_DOWN));
System.out.println(new BigDecimal(value).setScale(4,BigDecimal.ROUND_DOWN));
System.out.println(BigDecimal.valueOf(value).setScale(1,BigDecimal.ROUND_DOWN));
System.out.println(BigDecimal.valueOf(value).setScale(2,BigDecimal.ROUND_DOWN));
System.out.println(BigDecimal.valueOf(value).setScale(3,BigDecimal.ROUND_DOWN));
System.out.println(BigDecimal.valueOf(value).setScale(4,BigDecimal.ROUND_DOWN));
System.out.println(BigDecimal.valueOf(0.0).equals(BigDecimal.valueOf(0)));
}
上述代码的输出结果为:
24.93
24.92999999999999971578290569595992565155029296875
24.93
1.1
1.11
1.110
1.1109
1.1
1.11
1.111
1.1110
false