如何检查一个双精度值是否没有小数部分

我有一个双重值,我必须显示在我的 UI。 现在的条件是十进制值 double = 0 eg.-14.0 在这种情况下,我只需要在我的 UI 上显示14。 此外,这里字符的最大限制是5。

12.34整数值不能大于2位数,双精度数的小数值也不能大于2位数。

有什么最好的方法吗?

160509 次浏览

Compare two values: the normal double, and the double after flooring it. If they are the same value, there is no decimal component.

double d = 14.4;
if((d-(int)d)!=0)
System.out.println("decimal value is there");
else
System.out.println("decimal value is not there");

either ceil and floor should give the same out out put

Math.ceil(x.y) == Math.floor(x.y)

or simply check for equality with double value

x.y == Math.ceil(x.y)
x.y == Math.floor(x.y)

or

Math.round(x.y) == x.y

Use number formatter to format the value, as required. Please check this.

You could simply do

d % 1 == 0

to check if double d is a whole.

All Integers are modulo of 1. So below check must give you the answer.

if(d % 1 == 0)

You probably want to round the double to 5 decimals or so before comparing since a double can contain very small decimal parts if you have done some calculations with it.

double d = 10.0;
d /= 3.0; // d should be something like 3.3333333333333333333333...
d *= 3.0; // d is probably something like 9.9999999999999999999999...


// d should be 10.0 again but it is not, so you have to use rounding before comparing


d = myRound(d, 5); // d is something like 10.00000
if (fmod(d, 1.0) == 0)
// No decimals
else
// Decimals

If you are using C++ i don't think there is a round-function, so you have to implement it yourself like in: http://www.cplusplus.com/forum/general/4011/

Interesting little problem. It is a bit tricky, since real numbers, not always represent exact integers, even if they are meant to, so it's important to allow a tolerance.

For instance tolerance could be 1E-6, in the unit tests, I kept a rather coarse tolerance to have shorter numbers.

None of the answers that I can read now works in this way, so here is my solution:

public boolean isInteger(double n, double tolerance) {
double absN = Math.abs(n);
return Math.abs(absN - Math.round(absN)) <= tolerance;
}

And the unit test, to make sure it works:

@Test
public void checkIsInteger() {
final double TOLERANCE = 1E-2;
assertThat(solver.isInteger(1, TOLERANCE), is(true));


assertThat(solver.isInteger(0.999, TOLERANCE), is(true));
assertThat(solver.isInteger(0.9, TOLERANCE), is(false));


assertThat(solver.isInteger(1.001, TOLERANCE), is(true));
assertThat(solver.isInteger(1.1, TOLERANCE), is(false));


assertThat(solver.isInteger(-1, TOLERANCE), is(true));


assertThat(solver.isInteger(-0.999, TOLERANCE), is(true));
assertThat(solver.isInteger(-0.9, TOLERANCE), is(false));


assertThat(solver.isInteger(-1.001, TOLERANCE), is(true));
assertThat(solver.isInteger(-1.1, TOLERANCE), is(false));
}