java 如何在Java中将浮点数转换为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29315788/
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
How can I convert float to integer in Java
提问by Marko Petri?evi?
I need to convert a float number into an integer.
我需要将浮点数转换为整数。
Can Java automatically convert float number into integers? If so, do normal rounding rules apply (e.g. 3.4 gets converted to 3, but 3.6 gets converted to 4)?
Java可以自动将浮点数转换为整数吗?如果是这样,是否适用正常的舍入规则(例如,3.4 转换为 3,但 3.6 转换为 4)?
采纳答案by Roy Shmuli
You have in Math library function round(float a)
it's round the float to the nearest whole number.
您在 Math 库函数round(float a)
中将浮点数四舍五入到最接近的整数。
int val = Math.round(3.6); \ val = 4
int val2 = Math.round(3.4); \ val2 = 3
回答by cloudy_weather
回答by Ori Lentz
Math.round(3.6) would do that for you.
Math.round(3.6) 会为你做到这一点。