-1

我编写了一个代码,将双数分为整数和小数部分,但它只给出了最多 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);
4

2 回答 2

1

这是我认为您想要的尝试。我将结果保留为字符串形式,既可以在小数部分保留前导零,也可以避免溢出。如果你想做算术而不是显示,我建议将 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
于 2013-09-02T14:10:07.347 回答
1

也许您可以使用java.lang.Math.floor(double)整数部分,然后从原始数字中减去它以获得小数部分。(如果这不能满足您对负数的要求,则Math.ceiling(double)在数字为负数时使用整数部分。)

于 2013-09-01T20:35:27.640 回答