Java将浮点数转换为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2182924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java convert float to integer
提问by Sawyer
I want to do an operation like this : if the given float numbers are like 1.0 , 2.0 , 3.0 , I want to save them to database as integer (1,2,3 ), if they are like 1.1 , 2.1 , ,3.44 , I save them as float. what's the best solution for this problem using java ? The corresponding field in database is type of varchar.
我想做这样的操作:如果给定的浮点数像 1.0 、 2.0 、 3.0 ,我想将它们作为整数 (1,2,3 ) 保存到数据库中,如果它们像 1.1 、 2.1 、 ,3.44 ,我将它们保存为浮动。使用 java 解决此问题的最佳解决方案是什么?数据库中对应的字段为varchar类型。
采纳答案by fastcodejava
Just try int i = (int) f;.
试试吧int i = (int) f;。
EDIT : I see the point in the question. This code might work :
编辑:我看到了问题的重点。此代码可能有效:
int i = (int) f;
String valToStore = (i == f) ? String.valueOf(i) : String.valueOf(f);
回答by Bozho
String result = "0";
if (floatVar == Math.floor(floatVar)) {
result = Integer.toString((int) floatVar);
} else {
result = Float.toString(floatVar);
}
The if-clause checks whether the number is a whole number - i.e. if it is equal to the result of rounding it down to the closest whole value.
if 子句检查数字是否为整数 - 即它是否等于将其向下舍入到最接近的整数值的结果。
But this is very odd requirement indeed, and perhaps you should reconsider the need for such a thing.
但这确实是非常奇怪的要求,也许您应该重新考虑是否需要这样的东西。
回答by Philippe
Not sure this is the best solution, but you can try to write a method like this :
不确定这是最好的解决方案,但您可以尝试编写这样的方法:
String convertToString(Float f) {
if (f.toString().endsWith(".0"))
return f.intValue().toString();
else
return f.toString();
}
回答by Garg Unzola
Seems like you want to save Floats with no trailing numbers as Integers, while saving those with significant trailing numbers as Floats. I would rather just save it all as Float to the DB, but it's your question so here's my answer:
似乎您想将没有尾随数字的浮点数保存为整数,同时将具有重要尾随数字的浮点数保存为浮点数。我宁愿将其全部保存为 Float 到数据库,但这是您的问题,所以这是我的答案:
/**
* Method to determine if trailing numbers are significant or not. Significant
* here means larger than 0
*
* @param fFloat
* @return
*/
public static boolean isTrailingSignificant(Float fFloat)
{
int iConvertedFloat = fFloat.intValue();// this drops trailing numbers
// checks if difference is 0
return ((fFloat - iConvertedFloat) > 0);
}
This is how you would use this method:
这是您将如何使用此方法:
Number oNumToSave = null;
if (isTrailingSignificant(fFloat))
{
// save float value as is
oNumToSave = fFloat;
}
else
{
// save as int
oNumToSave = fFloat.intValue();// drops trailing numbers
}
After that, you can do the database operation using the variable oNumToSave.
之后,您可以使用变量 oNumToSave 进行数据库操作。

