我编写了一个代码,将双数字分成整数和分数部分,但它给出的数字只有10位数的正确答案(小数部分+小数部分),我如何分隔大于10位的双数?
double num, temp;
int j=1;
int whole,frac;
num= 122.007094;
temp= num;
whole=(int)num;
// FOR THE FRACTION PART
do{
j=j*10;
}while((temp*j)%10!=0);
j=j/10;
frac= (int)(num*j)-(whole*j);
System.out.println("Double number= "+num);
System.out.println("Whole part= "+whole+" fraction part= "+frac);
答案 0 :(得分:1)
也许您可以将java.lang.Math.floor(double)
用于整数部分,然后从原始数字中减去该数字以获得小数部分。 (如果这不能做你想要的负数,那么当数字为负时,使用Math.ceiling(double)
作为整数部分。)
答案 1 :(得分:1)
这是对我想要的思考的尝试。我将结果保留为String形式,以保留小数部分中的前导零,并避免溢出。如果你想做算术而不是显示,我建议将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