2014-10-08 138 views
2

我需要將float轉換爲int,就好像逗號被刪除一樣。 實施例: 23.2343f - > 232343Java浮點「刪除」逗號

private static int removeComma(float value) 
{ 
    for (int i = 0; ; i++) { 
     if((value * (float)Math.pow(10, i)) % 1.0f == 0.0f) 
      return (int)(value * Math.pow(10, i)); 
    } 
} 

問題是與舍入數目。例如,如果我通過23000.2359f,則它變成23000236,因爲它將輸入四捨五入到23000.236。

+1

難道你只是使用'(int)(value * 10000f)'或'Math.floor(value * 10000f)'? – OldCurmudgeon 2014-10-08 15:00:59

回答

7

的Java float沒有那麼多的精度,可以用

float f = 23000.2359f; 
System.out.println(f); 

其輸出

23000.236 

爲了得到你想要的輸出,你可以使用一個像double

double d = 23000.2359; 
String v = String.valueOf(d).replace(".", ""); 
int val = Integer.parseInt(v); 
System.out.println(val); 

輸出是(要求的)

230002359 
+0

很好的解決方法。你可以添加到這個沒有錯誤的數字的答案。我認爲它是15或16. – UniversE 2014-10-08 14:39:13

+0

這很不錯,但如果數字後面有一個e,該怎麼辦? (2343.4323e2 - > 23434323e2 - > Integer.parseInt異常) – 2014-10-08 14:46:22

+0

@RandomNoob然後你需要使用像你在你的問題中發佈的算法。但是你不能做的,是假設'double'和/或'float'具有無限精度(因爲它們不)。 – 2014-10-08 14:47:47

-3

您必須找到一種方法來獲得第一位小數點後的位數。假設它是n。然後乘以10倍數n

double d= 234.12413; 
String text = Double.toString(Math.abs(d)); 
int integerPlaces = text.indexOf('.'); 
int decimalPlaces = text.length() - integerPlaces - 1; 
+0

簡單的問題:爲什麼? – BackSlash 2014-10-08 14:34:43