5

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.

  • 1
    You want to increment the decimals by `0.02`? If so, you can add `0.02` to `i` instead of `0.05`. Also, you can remove those `parseFloat` calls since you're just hardcoding your values anyway :) – Arnelle Balane Sep 11 '15 at 16:25
  • 1
    `parseFloat` is for string representations of numbers, you should remove those. – TomSlick Sep 11 '15 at 16:27

4 Answers4

3

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>
Community
  • 1
  • 1
James Brierley
  • 4,630
  • 1
  • 20
  • 39
2

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/>");
}
Vibhesh Kaul
  • 2,593
  • 1
  • 21
  • 38
1

You can simply using int value to create decimal by devide it by 100. Change your code as beloow.

$("#btn").click(function(){
    for(i = 0; i <= 200; i += 2){
        $("#paragraph").append(eval(i / 100) + "<br/>");
    }
});

for example please follow https://jsfiddle.net/jffmzjuL/

1

Assuming that you want to increment the iteration by 0.02, you can try the following loop:

for (var i = 0; i < 21; i += 2) {
   console.log(i / 100);
}

jQuery("#btn").on("click", function() {
  for (var i = 0; i < 21; i += 2) {
    var result = i / 100;
    jQuery("#list").append("<li>" + result + "</li>");
  }
});

Update #1 (Added working example)

jQuery("#btn").on("click", function() {
  for (var i = 0; i < 21; i += 2) {
    var result = i / 100;
    jQuery("#list").append("<li>" + result + "</li>");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
  <head>
    <title></title>
  </head>
  <body>
    <button id="btn">Generate Numbers</button>
    <ul id="list">
    </ul>
  </body>
</html>
Eder
  • 1,874
  • 17
  • 34