Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a number has a decimal place/is a whole number

I am looking for an easy way in JavaScript to check if a number has a decimal place in it (in order to determine if it is an integer). For instance,

23 -> OK 5 -> OK 3.5 -> not OK 34.345 -> not OK 
if(number is integer) {...}
like image 481
Hans Avatar asked Feb 20 '10 22:02

Hans


People also ask

How do you check if a number is whole or decimal?

function number_test(n) { var result = (n - Math. floor(n)) !== 0; if (result) return 'Number has a decimal place. '; else return 'It is a whole number.

How do you figure out if a number is a whole number?

You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point. If result is equal to zero then the number is a whole number.

What decimal place is a whole number?

The whole number portion of a decimal number are those digits to the left of the decimal place. Example: In the number 23.65, the whole number portion is 23. In the number 0.024, the whole number portion is 0.

How do you check if something is a whole number in JavaScript?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .


1 Answers

Using modulus will work:

num % 1 != 0 // 23 % 1 = 0 // 23.5 % 1 = 0.5 

Note that this is based on the numerical value of the number, regardless of format. It treats numerical strings containing whole numbers with a fixed decimal point the same as integers:

'10.0' % 1; // returns 0 10 % 1; // returns 0 '10.5' % 1; // returns 0.5 10.5 % 1; // returns 0.5 
like image 87
Andy E Avatar answered Sep 16 '22 15:09

Andy E