problems increasing decimal within loop for

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

I would like the values to vary with every 0,1 , what is the problem with my code?

follow jsFiddle: link

    
asked by anonymous 10.05.2016 / 17:01

2 answers

0

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

In practice for your problem you can do this:

var nr = i.toFixed(1);

In this way you limit the "tail" from number to tenths.

The code could look 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: link

    
10.05.2016 / 17:17
0

You're doing it right, the problem is with the lack of precision when dealing with floating points. to correct this problem use the toFixed fuction present in the numbers of type float passing as paramentro for the function the number of decimals that you want to display, I think it would be good 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);
    
10.05.2016 / 17:29