0

I need to check whether 4096.0 is same as it's integer form. (In JAVA language)

Is this the correct way?

Math.ceil(number) == Math.floor(number);

If not, then please suggest the correct way to do this.

Gautham M
  • 4,816
  • 3
  • 15
  • 37
  • 1
    what is the type of `number` ? – Hưng Chu Jun 03 '21 at 16:19
  • 3
    Are you sure you *want* to? See [Is floating point math broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). Floating-point values are often not quite exact, so the value you *think* is 4096.0 could actually be computed as 4096.000000000000000000000000003, due to floating-point arithmetic rules. – Silvio Mayolo Jun 03 '21 at 16:20
  • 1
    Fun exercise, @sushmita: Run this code: `double x = 0.1 + 0.2; x = x * 10;`. You'll find that, mysteriously, this `x` is __not__ an integer (it is 3.0000000000000004, which is not equal to 3 casted to a double). The general takeaway is that `double` and `float` are datatypes that fundamentally cannot do what you want here. Use something else. For example, if doing finance, represents cents, in a `long`. Or use `BigDecimal` (and read up - that is a very complicated API because asking computers to do this stuff is just intractably difficult). – rzwitserloot Jun 03 '21 at 16:28
  • `double d=4096.00000; BigDecimal bd = BigDecimal.valueOf(d); String s = bd.stripTrailingZeros().toPlainString(); boolean isInteger = s.indexOf(".")==-1;` – Paul Jun 03 '21 at 16:35

0 Answers0