简体   繁体   English

浮点舍入(Java)

[英]Floating point rounding (in java)

What is the best way of determining if a given float(or double) has no significant decimal places. 确定给定浮点数(或双精度数)是否没有小数位的最佳方法是什么。

f(234.0)  = true
f(34.45)  = false
f(3.1322) = false

ie equivalent of 即相当于

EQ(((int)number) * 1.0 , number)

where EQ is a given method to compare floating points and it is OK to assume that the float fits in an integer. EQ是比较浮点数的给定方法,可以确定浮点数适合整数。

Math.rint(x) == x

Math.rint() returns a double , so it also works for large numbers where the long result of Math.round() overflows. Math.rint()返回double ,因此它也适用于Math.round()long结果溢出的大量数字。

Note that this also gives true for positive and negative infinity. 请注意,这对于正无穷大和负无穷大也适用。 You can explicitly exclude them by Math.rint(x) == x && !Double.isInfinite(x) . 您可以通过Math.rint(x) == x && !Double.isInfinite(x)明确排除它们。

Round the value to the nearest integer, and calculate the absolute difference to the actual value. 将值四舍五入到最接近的整数,然后计算出与实际值的绝对差。

If that difference is less than a certain percentage of the actual value you are close "enough". 如果该差异小于实际值的某个百分比,则表示您“足够”。

You could try something like this: 您可以尝试这样的事情:

public static boolean f(double d) {
    return d % 1 == 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM