-1

I have this:

if (dTotal % 1 !== 0 || nTotal % 1 !== 0) {
   //stuff  
}

and the variable nTotal is the number 0.2, but the stuff in the if statement is happening. I know that the two variables are numbers, not strings. I just want the things in the if statement to happen if both nTotal and dTotal are whole numbers.

CPC
  • 163
  • 5
  • 17
  • possible duplicate of [How to check if a variable is an integer in Javascript?](http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript) – Jason Baker Nov 05 '14 at 02:06
  • `0.2 % 1 === 0.2`, which you can test in a Javascript console – Jason Baker Nov 05 '14 at 02:07
  • what is the value of dTotal? – 3Dom Nov 05 '14 at 02:10
  • dTotal has a value of 1 – CPC Nov 05 '14 at 02:17
  • It's not really a duplicate, since he's not asking how to test for integer-ness, but rather why his `if` statement is not working, which is due to a typo (forgot to apply `!` to the `if` condition). –  Nov 05 '14 at 02:45

4 Answers4

3
if (parseInt(dTotal) == parseFloat(dTotal)
 && parseInt(nTotal) == parseFloat(nTotal)) {
  alert("success");
}

If both ARE numbers, then this will work.

philz
  • 1,012
  • 6
  • 11
  • I'm super new to Javascript, so I don't know much about it, so what exactly is that doing? – CPC Nov 05 '14 at 02:15
  • parseInt converts a string or integer to its integer value, so 1.2 => 1. parseFloat does the same, except to a float, so 1.2 => 1.2. When you compare the two, as parseInt always goes to an integer, they can only be the same if the number provided is an integer. – philz Nov 05 '14 at 02:16
2
if (!(dTotal % 1 !== 0 || nTotal % 1 !== 0))

You need a NOT before the OR clause. Your original code was saying:

If the remainder of dTotal divided by one is not 0 (meaning its not an integer) OR If the remainder of nTotal divided by one is not 0 (meaning its not an integer) then do something...

You want the opposite of that, so add the exclamation point as I have done.

Isaac Ray
  • 1,351
  • 9
  • 17
2

The correct answer is from @IsaacRay; you simply had the polarity of your test reversed.

The accepted answer, for what it's worth, is about ten times slower than using %.

You could also use Math.floor which is about as fast as %:

if (Math.floor(dTotal) === dTotal && Math.floor(nTotal) === nTotal) {

Math.floor basically removes the decimal part of the number. By comparing it to the original number, we can see if the number is an integer.

You might be tempted to use Number.isInteger if available, but it is very slow; twice as slow as even parseInt, twenty times as slow as % or Math.floor.

JSPerf: http://jsperf.com/testing-if-a-number-is-an-integer

0
dTotal % 1 !== 0 

That part is probably true, which is why the if condition is true. (You're using or (||) not and (&&))

3Dom
  • 795
  • 3
  • 10
  • 22