1

I need my code to only accept whole numbers, no decimals and should prompt an error when a decimal gets entered. I don't want a new function , I'm hoping I can just add lines to my function but I don't know what I need to add.

function number_function() {

  number = parseInt(prompt('Enter a positive integer:'));


  if (number < 0) {
    alert('Error! Factorial for negative number does not exist. But I will show you the positive number');
    number = number * -1;
    let n = 1;
    for (i = 1; i <= number; i++) {
      n *= i;
    }
    alert("The factorial of " + number + " is " + n + ".");


  } else if (number === 0) {
    alert("Please enter a number greater than 0");
  } else {
    let n = 1;
    for (i = 1; i <= number; i++) {
      n *= i;
    }
    alert("The factorial of " + number + " is " + n + ".");
  }
}

number_function();
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73
  • "I don't want a new function" why though? Functions are good we shd use them ... – Rabhi salim Dec 07 '20 at 14:06
  • Should the user be able to use thousands separators? – Mark Baijens Dec 07 '20 at 14:12
  • Does this answer your question? [Check if a number has a decimal place/is a whole number](https://stackoverflow.com/questions/2304052/check-if-a-number-has-a-decimal-place-is-a-whole-number) – Liam Dec 07 '20 at 16:10

2 Answers2

2

You can do this to check if the number has decimals

const val = 10.7 % 1;

if (val !== 0) {
  console.log('has decimals');
} else {
  console.log('has no decimal');
}
firatozcevahir
  • 892
  • 4
  • 13
0

JavaScript provides the built-in function Number.isInteger(n)

Rick
  • 1,391
  • 8
  • 11