【问题标题】:How do I round to the nearest ten? [duplicate]如何四舍五入到最接近的十位? [复制]
【发布时间】:2017-02-11 00:04:29
【问题描述】:

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

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

【问题讨论】:

标签: java rounding


【解决方案1】:

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

【讨论】:

  • 如果除以 10d 或 10.0,num 可以是任何(原始)数字。
  • 正确,已编辑。 @彼得
【解决方案2】:
answer = ((num+5)/10)*10; // if num is int

其中numint 并且要了解更多信息,请阅读此问题。 How to round a number to n decimal places in Java.
编辑:
如果numdouble,则按照@PeterLawrey 的建议将类型转换添加到表达式(long)((num+5)/10)

【讨论】:

  • 你确定吗?如果 num 是 14.0,那么这将评估为 20。
  • 我可能有一个高级的时刻,但我最后一次检查时,(14.0 + 5) / 10 是 1.9,四舍五入时变成 2.0。请记住,Math.round 实现了德式四舍五入。
  • 将 int 强制转换为 int 是多余的,如果它已经很长,则更糟。
  • @sinsuren 如果它是双重的,则需要演员,但如果可能的话,你会使用 long 。这是 OP 问题的一个整数。
  • @PeterLawrey 我已根据您的建议进行了更改。感谢您提高回答质量。
猜你喜欢
  • 2017-05-22
  • 2014-12-14
  • 1970-01-01
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
  • 2012-01-25
相关资源
最近更新 更多