-2

I need to check if a variable is a whole number and i have a lot of easy solutions.

The first one is

if (floor(foobar) == foobar)

And the other one is

if(d % 1 == 0)

The another one is convert this number to string and split by dot(.) and check second number is "00" of not

d.toString().split('.')[1/]=="00"

But i think it is not a best practice.

A lot of these type of way, i want a standerd solution which is acceptable by all.

Community
  • 1
  • 1
mayank
  • 2,615
  • 2
  • 23
  • 18

3 Answers3

9

I'd probably go with

(d % 1) < epsilon

from the comment thread in the linked question. It's slower than both your examples so you can probably only do it a few million times per second as opposed to a few million times per second. On the plus side it handles floating point drift and min and max values quite well

James
  • 9,774
  • 5
  • 34
  • 58
  • 2
    +1 for "a few million as opposed to a few million". Premature optimization is indeed the root of all evil. – CodeCaster Aug 11 '15 at 10:04
0

IMO, (int)d == d is the best in regards to readability.

I don't know about execution times, though.

Nathan
  • 1,520
  • 1
  • 12
  • 21
0

In C# you can use built in function int.TryParse()

int x;
bool result= int.TryParse(integerNumber.ToString(), out x);

if result is true then integer otherwise not.

kode_anil
  • 66
  • 1
  • 6
  • Not quite. Not all whole number `doubles` are valid integers. `int.TryParse((int.MaxValue + 1.0).ToString(), out _)` return `false`! – Pharaz Fadaei Sep 01 '21 at 21:28