w3resource

JavaScript: Check if a number is a whole number or has a decimal place

JavaScript Math: Exercihse-38 with Solution

Write a JavaScript function to check if a number is a whole number or has a decimal place.

Note : Whole Numbers are simply the numbers 0, 1, 2, 3, 4, 5, ... (and so on). No Fractions!
Test Data :
console.log(number_test(25.66));
"Number has a decimal place."
console.log(number_test(10));
"It is a whole number."

Visual Presentation:

JavaScript: Math - Check if a number is a whole number or has a decimal place.

Sample Solution:

JavaScript Code:

// Define a function named number_test that checks if a number has a decimal place.
function number_test(n)
{
   // Calculate the difference between n and its floor value, and check if it is not equal to zero.
   var result = (n - Math.floor(n)) !== 0; 
   
   // If result is true, return 'Number has a decimal place.'; otherwise, return 'It is a whole number.'
   if (result)
      return 'Number has a decimal place.';
   else
      return 'It is a whole number.';
}

// Output the result of testing if 25.66 has a decimal place to the console.
console.log(number_test(25.66));

// Output the result of testing if 10 has a decimal place to the console.
console.log(number_test(10));

Output:

Number has a decimal place.
It is a whole number.

Flowchart:

Flowchart: JavaScript Math- Check if a number is a whole number or has a decimal place

Live Demo:

See the Pen javascript-math-exercise-38 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to limit a value inside a certain range.
Next: Write a JavaScript function to print an integer with commas as thousands separators.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-math-exercise-38.php