该程序基于BigDecimal和scale概念,如
assylias’s answer所示,但修改为无条件使用最大可能的所需比例.这允许在数字流中使用相同的比例,而无需在处理任何数字之前查看所有数字.成本是它通常会返回不必要的大BigInteger值.
比例因子“1e1074”基于以下观察:所有有限双数是Double.MIN_VALUE的整数倍,其在小数点后具有1074个十进制数字.没有double可以在小数点后有更多的十进制数字.
import java.math.BigDecimal;
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
testit(Double.MIN_VALUE);
testit(Double.MAX_VALUE);
testit(0);
testit(1.0);
testit(Math.E);
testit(Math.PI);
}
private static void testit(double d) {
double roundTrip = scaledIntegerToDouble(doubleToScaledInteger(d));
if (d != roundTrip) {
System.out.println("ERROR: " + d + " " + roundTrip);
}
}
public static final BigDecimal scale = new BigDecimal("1e1074");
public static BigInteger doubleToScaledInteger(double d) {
BigDecimal bd = new BigDecimal(d).multiply(scale);
return bd.toBigIntegerExact();
}
public static double scaledIntegerToDouble(BigInteger bi) {
BigDecimal bd = new BigDecimal(bi).divide(scale);
return bd.doubleValue();
}
}