0

I have a piece of code that counts from 0 to a specified number with a specified delay.

The problem is that it adds by 1 and I want it to add by 0.01

How to do it? the code is as follows:

    <!DOCTYPE HTML>
<html>
<head>
<style>body{font:11px verdana;color:#555;}</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var max = 20;// set with php
$(incCounter);
function incCounter() {
    var currCount = parseInt($('.counter').html());
    $('.counter').text(currCount+1);
    if (currCount+1 != max) {
        setTimeout(incCounter,50);
    }
}
</script>
</head>
<body>
<div class="counter">0</div>
</body>
</html>
6
  • 4
    It surely cannot be as simple as $('.counter').text(currCount + 0.01), right? Commented Nov 3, 2012 at 23:07
  • 1
    have you tried num.toFixed(2) Commented Nov 3, 2012 at 23:08
  • 3
    Did you try running that function, and not just wrapping it ? Commented Nov 3, 2012 at 23:11
  • @adeneo sure I have a test page and trying to test every suggestion Commented Nov 3, 2012 at 23:13
  • What result? What exactly doesn't work with @slashingweapon answer? And, as a sidenote, do you know that each time someone reports a 'does not work' bug into the public (instead of just DESCRIBING what the h doesn't work), a cute kitten cringes in pain somewhere? Commented Nov 3, 2012 at 23:14

1 Answer 1

3

I haven't tested this, but try...

function incCounter() {
    var currCount = parseFloat($('.counter').html());
    currCount += .01;
    $('.counter').text( currCount.toFixed(2) );
    if (currCount < max)
        setTimeout(incCounter,50);
}

JS Fiddle to play with.

Sign up to request clarification or add additional context in comments.

2 Comments

Altough it's against my policy to upvote answers for trivial programming tasks, still +1 - quite a nice implementation. ) Will add a fiddle for that.
+1 because you beat my fiddle by a whole 7 minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.