1

I'm trying to do something really stupid, but maybe it will be my careless mistake ... In short, how is it possible that in a simple function like this:

function limitFunc(name){
  var domain=prompt(`Inserisci il dominio della funzione`);
  var sx=domain-0.2;
  var dx=domain+0.2;
  console.log(`sx`,sx, `dx:`,dx);
  //console.table(graph.limitCalculation(name, domain));
}

If I then write 1 with the prompt, the dx variable then calculated gives me a number multiplied by 10.

For example if I write 1: chrome console

Thanks for the help anyway

  • 3
    `prompt()` always returns a string, so you have to convert those values to numbers before doing math (especially `+`). – Pointy Jun 01 '22 at 14:19
  • 1
    You should first convert `domain` to a number, you are working with a string (which has a different meaning for the `+` operator) – UnholySheep Jun 01 '22 at 14:19
  • `"1" + 0.2` = `"10.2"`. `1 + 0.2` = `1.2` (approximately, but due to floating point math it might not be exactly 1.2) – WOUNDEDStevenJones Jun 01 '22 at 14:20

1 Answers1

1

prompt returns a string.

All you need to do is convert your string into a number, basically:

function limitFunc(name) {
    let domain = prompt(`Inserisci il dominio della funzione`);
    domain = +domain; // converted string into number
    const sx = domain - 0.2;
    const dx = domain + 0.2;
    console.log(`sx:`, sx, `dx:`,dx);
}

limitFunc();

Obviously, you'd want to check if the user prompts a valid answer (i.e. a number).

pistou
  • 2,799
  • 5
  • 33
  • 60