Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create loop with decimals in Jquery

I need to create a loop that can iterate with decimal, something like this:

$("#btn").click(function(){
    for(i =parseFloat(0.00); i <= 2.00;i=parseFloat(i+0.05)){
        $("#paragraph").append(i+"<br/>");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" id="btn" value="Create decimals" />
<p id="paragraph"></p>

But the result is not as expected, I need something like this:

  • 0.02
  • 0.04
  • 0.06
  • ....
  • 1.04
  • ....
  • 1.99
  • ....
  • 2

Thanks for your help.

like image 723
Steven Arturo Brenes González Avatar asked Sep 11 '15 16:09

Steven Arturo Brenes González


2 Answers

But the result is not as expected

When I run your code snippet, it prints some values like:

0.15000000000000002

This is because of how javascript handles floating points. The representation is not exact. The solution is to use the toFixed method, as shown in this answer.

$("#btn").click(function(){
    for(i = 0.00; i.toFixed(2) <= 2.00; i = i + 0.02){
        $("#paragraph").append(i.toFixed(2) + "<br/>");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" id="btn" value="Create decimals" />
<p id="paragraph"></p>
like image 183
James Brierley Avatar answered Oct 02 '22 20:10

James Brierley


As per your expected result you could simply do:

for (var i = 0.00; i <= 2.00; i += 0.02) {
$("#paragraph").append(i.toFixed(2)+"<br/>");
}
like image 37
PsyLogic Avatar answered Oct 02 '22 20:10

PsyLogic