2011-05-13 27 views
4

我在我的java程序中需要一個函數的一個小問題。我想檢查數字的總量,一個'雙'變量。 (例如:5應該返回1,5.0034應該返回5,和2.04應該返回3)我的功能是這樣的:在一個雙變量中獲取數字的問題

private int getDoubleLength (double a) { 
     int len = 0; 
     while (a != (int) a) { 
      a *= 10; 
     } 
     while (a > 1) { 
      len ++; 
      a/=10; 
     } 
     System.out.println(String.format("Double %f has %d digits.",a,len)); 
     return len; 
    } 

現在這個完美的作品,但是當我做一些數學計算,你得到的輕微雙倍誤差:我用cos(60)除以10,即0.5。答案應該是20.0,但程序給出了一個20.000000000000004(這個數字,我複製了它)。我的while循環卡住了,程序掛起。

任何想法? (或其他偉大的解決方案,用於檢查數字的數字!)

+1

雙重不能有精度超過17位,所以你應該停止,當你到17,你有另一個問題是,雙能比整數多。 MAX_VALUE會導致你的第一個循環無限地迭代。 – 2011-05-13 14:14:58

回答

1

toString()。length()應該解決它
記住減去'。'如果它在那裏,不應該被計算在內

+0

+1,但不應該是toString.length - 1(因爲這一點)? – 2011-05-13 14:16:37

+0

@凱:我在我的回答中提到了這個(第二行) – amit 2011-05-13 14:17:35

0

這是一個四捨五入的問題。我會使用字符串,計數字符,並決定哪些數字會被計入重要。

1

這就是我如何實現我的,簡單轉換爲字符串時,雙是大返回字符串與指數表示。即20000000會返回2.0E + 7,然後拆分將從這裏拆分,導致計數錯誤。我曾經BigDecimaltoPlainString()方法

protected int countDecimalDigits(Double d) { 
    BigDecimal deci = BigDecimal.valueOf(d); 
    int integerPlaces = 0; 
    int decimalPlaces = 0; 
    String text = deci.toPlainString(); 

    String[] integerDecimalSplit = text.split("\\."); 
    if (null != integerDecimalSplit[0]) { 
     integerPlaces = integerDecimalSplit[0].length(); 
    } 
    if (integerDecimalSplit.length > 1) { 
     decimalPlaces = integerDecimalSplit[1].length(); 
    } 
    return integerPlaces + decimalPlaces; 
}