If function with decimal numbers

Asked

Viewed 177 times

0

I am a designer and an adventurer in programming and eventually adapt some codes in projects. I have a situation here that I couldn’t handle on my own. The following code analyzes the value entered by the user in the form and, if the number entered is within one of the function ranges, the script gives an answer:

function analisar_valor() {
    var info_form = parseInt(document.getElementById("info_form").value);

    var resposta = info_form;
    console.log(resposta);

    if(resposta < 0.005){
      document.getElementById("resposta").innerHTML = '<p>resposta 1</p>';
    }else if(resposta >= 0.005 && resposta <= 0.499){
      document.getElementById("resposta").innerHTML = '<p>resposta 2</p>';
    }else if(resposta >= 0.5 && resposta <= 2.999){
      document.getElementById("resposta").innerHTML = '<p>resposta 3</p>';
    }else if(resposta >= 3 && resposta <= 9.999){
      document.getElementById("resposta").innerHTML = '<p>resposta 4</p>';
    }else if(resposta >= 10 && resposta <= 50){
      document.getElementById("resposta").innerHTML = '<p>resposta 5</p>';
    }else if(resposta > 50){
      document.getElementById("resposta").innerHTML = '<p>resposta 6</p>';
    }
}

The problem is that the first answer of "elseif" (answer 2) does not return because it is not interpreting decimal numbers. Any decimal value entered gives the answer to "if", and then from the value "1" it gives the answer 3.

How can I get it to consider decimal numbers? I found something about parseFloat, but I don’t know how to insert it into the function.

1 answer

3


  • Adding: when using the parseInt() the value is converted to an integer if the value in question is a decimal number, it shall be rounded down. The parseFloat() converts to a float type, which supports decimal values.

  • Caraca, perfect, @rLinhares. I had not attacked this parseint. Solved, bingo! Thanks!

  • mass!! but the answer was given by wensiso.. just edited to put the references of the methods for you to take a look ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.