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) {...}
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.
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.
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.
The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With