如何防止整数值被截断

时间:2013-02-06 00:37:33

标签: java

String s = "128166947252913248";
DecimalFormat df = new DecimalFormat("##########################.########");
Double oldTime1 = new Double(s); 
Double oldTime2 = new Double("128166947252913249"); 
Double oldTime3 = new Double("128166947252913247");
Double newTime = new Double("116444736000000000");
System.out.println(newTime.longValue());
System.out.println(df.format(oldTime1));
System.out.println(oldTime1-newTime);
System.out.println(df.format(oldTime1-newTime));
System.out.println(df.format(oldTime3-newTime));

输出是:

116444736000000000
128166947252913248
1.1722211252913248E16
11722211252913248
11722211252913248

这是我正在处理的代码。我无法阻止双变量在最后一个变量处被截断。请帮助我获取一个值而不被截断。

2 个答案:

答案 0 :(得分:4)

Double对十八位十进制数字的精确度不够:64-bit IEEE-754 numbers have at most 17 decimal digits。您应该使用BigDecimal来获得无限精度。

答案 1 :(得分:3)

尝试使用BigDecimal

String s = "128166947252913248";
DecimalFormat df = new DecimalFormat(
        "##########################.########");
BigDecimal oldTime1 = new BigDecimal(s);
BigDecimal oldTime2 = new BigDecimal("128166947252913249");
BigDecimal oldTime3 = new BigDecimal("128166947252913247");
BigDecimal newTime = new BigDecimal("116444736000000000");
System.out.println(newTime.longValue());
System.out.println(df.format(oldTime1));
System.out.println(oldTime1.subtract(newTime));
System.out.println(df.format(oldTime1.subtract(newTime)));
System.out.println(df.format(oldTime3.subtract(newTime)));