problems increasing decimal place within loop for

Asked

Viewed 113 times

3

var iniciaEm = 0;
var terminaEm = 20;
var variacao = 0.1;
var s = "";
var str = "";
for(var i =iniciaEm; i<=terminaEm; i=i+variacao){
     str += i; 
    s += "<option value=\""+i+"%\">"+i+"%</option>";
}

$("#teste").append(s);

// retorno:
    0
    0.1
    0.2
    0.30000000000000004
    0.4
    0.5
    0.6
    0.7
    0.7999999999999999
    0.8999999999999999
    0.9999999999999999
    1.0999999999999999

would like the values to vary with each 0,1, what’s wrong with my code?

follow the jsFiddle: https://jsfiddle.net/7wx1t5yb/

2 answers

0


Javasript has problems with known numerical calculations and inaccuracies. There is a question and many good answers about it here.

In practice for your problem you can do so:

var nr = i.toFixed(1);

so you limit the number’s "tail" to tenths.

The code could be like this:

for (var i = iniciaEm; i <= terminaEm; i = i + variacao) {
    var nr = i.toFixed(1);
    str += nr + "<br />";
    s += "<option value=\"" + nr + "%\">" + nr + "%</option>";
}

jsFiddle: https://jsfiddle.net/7x2hqnhm/

0

You’re doing it right, the problem is with the lack of precision when dealing with floating points. to fix this problem use the toFixed fution present in the numbers of type float passing as parameter to the function the number of decimal places you want to display, I think would look good the value 2. For example:

var iniciaEm = 0;
var terminaEm = 20;
var variacao = 0.1;
var s = "";
var str = "";
for(var i =iniciaEm; i<=terminaEm;i+=variacao){
    str += i.toFixed(2)+"<br />"; 
    s += "<option value=\""+i.toFixed(2)+"%\">"+i.toFixed(2)+"%</option>";
}

$("#teste").append(s);
$(".resultado").append(str);

Browser other questions tagged

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