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:
Thanks for your help.
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>
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/>");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With