【问题标题】:How do I round a float but keep it a float (i.e. without converting it to int)?如何舍入浮点数但保持浮点数(即不将其转换为 int)?
【发布时间】:2018-06-24 02:07:45
【问题描述】:

例如,我的结果是圆形面积 = 4.3,我的问题是“当我得到大于 0.5 的数字时[例如(4.6、4.7、4.8、4.9)],我希望它给我 5.0,但是如果小于 0.5 [4.4, 4.3, 4.2, 4.1] 则显示 4.0'

我尝试了Math.round(),但它像 [4] 一样将 float 转换为 int,但我不想将其转换为 int

有没有办法做到这一点?

这是我的代码:

private float radius;
private double result;

public void show(float x)
{
    this.radius = x;
    this.result=Math.pow(x,2)*Math.PI;

    System.out.println("result is: "+result);
}

显然,我希望在一个函数中同时使用方法(Math.floor()) 和 (Math.ceil()) 谢谢

【问题讨论】:

  • Math.round(4.5f) 将返回 5 并完全按照您的意愿行事。将 int 转换为 float/double 真的一点也不难。
  • 或者,既然你知道这个区域总是积极的,你可以使用Math.floor( area + .5 )
  • (float)Math.round(x) 使 int 再次成为浮点数。然而floatdouble 是一个近似值(2 的幂和),没有固定的小数位数,5.3 实际上有一个小错误,10000*5.3 不会正好是 53000。
  • @OHGODSPIDERS 谢谢,=)
  • Windows 计算器内部不使用浮点数/双精度数,而是类似于 java 中的 BigDecimal。

标签: java floating-point simplify


【解决方案1】:

Math.rint 可能与您要查找的内容最接近。注意是rounds half to even

【讨论】:

    猜你喜欢
    • 2021-10-09
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2013-02-17
    相关资源
    最近更新 更多