Search code examples
javascriptpromptaddition

Doubts in the use of int variables


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


Solution

  • 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).