Java 如何四舍五入到最接近的十位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39824914/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:28:39  来源:igfitidea点击:

How do I round to the nearest ten?

javarounding

提问by Cmi

How can I round a number to the nearest ten with no if statements? For example, 98 to 100.

如何在没有 if 语句的情况下将数字四舍五入到最接近的十?例如,98 到 100。

int num = 87;
double t;
double d = 1.0 * num; // d = 87.0
t = d/100;
System.out.println(t);

回答by Zarwan

You can use Math.round(num/10.0) * 10.

您可以使用Math.round(num/10.0) * 10.

回答by sinsuren

answer = ((num+5)/10)*10; // if num is int

where numis intand to have more idea, read this quesiton. How to round a number to n decimal places in Java.
Edit:
if numis doubleadd typecasting to expression (long)((num+5)/10)as suggested by @PeterLawrey

这里numint和有更多的想法,请阅读本quesiton。 如何在 Java 中将数字四舍五入到 n 个小数位
编辑:
如果numdouble附加的类型转换,以表达(long)((num+5)/10)由@PeterLawrey建议