2014-10-08 112 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