ibrahimqd
ibrahimqd

Reputation: 45

Float sum with javascript (jquery)

i have code jquery but i want a plus 0.00001 for value every second

$(document).ready(function(){
     
	setInterval(function()
	{ 
			var id = $('.id').attr('rel');
			var st = (parseFloat(id) + parseFloat('0.00001')).toFixed(1);
			$('.id').html(st);
			$('.id').attr('rel',st);

	}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
// html output
<span class='id' rel='0.00001'>0.00001</span>

Upvotes: 1

Views: 4329

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

The issue is because you're rounding to 1 decimal place using toFixed(1). Change that to toFixed(5) and your code works fine. Although note that converting a string literal to a float is a little redundant, just use the float directly in the addition:

$(document).ready(function() {
  setInterval(function() {
    var id = $('.id').attr('rel');
    var st = (parseFloat(id) + 0.00001).toFixed(5);
    $('.id').html(st).attr('rel', st);
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
// html output
<span class="id" rel="0.00001">0.00001</span>

Upvotes: 1

Related Questions