这是我认为您想要的尝试。我将结果保留为字符串形式,既可以在小数部分保留前导零,也可以避免溢出。如果你想做算术而不是显示,我建议将 String 结果转换为 BigInteger,这样不会溢出。
import java.math.BigDecimal;
public class Test{
public static void main(String[] args){
double num1 = 122.007094;
double num2 = 1236758511.98746514;
testIt(num1);
testIt(num2);
testIt(1e7);
testIt(0.1);
testIt(0.12345678901234);
}
public static void testIt(double in) {
String[] result = doubleSplit(in);
System.out.println("num="+in+" whole="+result[0]+" fraction="+result[1]);
}
/**
* Split the decimal representation of a double at where the decimal point
* would be. The decimal representation is rounded as for Double.toString().
* @param in The double whose decimal representation is to be split.
* @return A two element String[]. The first element is the part
* before where the decimal point would be. The second element is the part
* after where the decimal point would be. Each String is non-empty, with
* "0" for the second element for whole numbers.
*/
public static String[] doubleSplit(double in) {
/* Use BigDecimal to take advantage of its toPlainString. The
* initial Double.toString uses its rounding to limit the
* number of digits in the result.
*/
BigDecimal bd = new BigDecimal(Double.toString(in));
String [] rawSplit = bd.toPlainString().split("\\.");
if(rawSplit.length > 1){
return rawSplit;
} else {
return new String[]{rawSplit[0], "0"};
}
}
}
输出:
num=122.007094 whole=122 fraction=007094
num=1.2367585119874651E9 whole=1236758511 fraction=9874651
num=1.0E7 whole=10000000 fraction=0
num=0.1 whole=0 fraction=1
num=0.12345678901234 whole=0 fraction=12345678901234