2011-01-12 42 views
11

如何檢查浮點數是否包含小數點,如2.10,2.45,12382.66而不是2.00,12382.00。我想知道這個號碼是否是「四捨五入」的。我怎樣才能做到這一點編程?檢查浮點數是否包含小數點

+1

這個C函數看着他們?如果你想要一個編程解決方案,那麼給我們提供更多信息。 – skaffman 2011-01-12 11:51:46

+2

(和你工作的語言。) – dkarp 2011-01-12 16:01:24

回答

5

如果你只關心兩位小數,通過計算bool hasDecimals = (((int)(round(x*100))) % 100) != 0;

在一般的情況下獲得的其餘部分中描述this topic得到一個小數部分,並將其與0

+2

這對我來說非常合適。我使用Objective-C btw。只要你知道你有多少小心評估,這是簡單的,並完成這項工作。您可以通過將10乘以您關心的小數點數量來修改它,以取代上述示例中出現的「100」,以使其更加靈活。 – idStar 2012-02-26 18:35:00

3

你可以這樣做:

float num = 23.345f; 
    int intpart = (int)num; 
    float decpart = num - intpart; 
    if(decpart == 0.0f) 
    { 
    //Contains no decimals 
    } 
    else 
    { 
    //Number contains decimals 
    } 
40

使用模量將工作:

if(num % 1 != 0) do something! // eg. 23.5 % 1 = 0.5

6

我使用的Objective C的

BOOL CGFloatHasDecimals(float f) { 
    return (f-(int)f != 0); 
} 
2
import java.lang.Math; 
public class Main { 
    public static void main(String arg[]){ 
     convert(50.0f); 
     convert(13.59f); 

    } 

    private static void convert(float mFloat){ 
     if(mFloat - (int)mFloat != 0) 
      System.out.println(mFloat); 
     else 
      System.out.println((int)mFloat); 
    } 
}