Reputation: 23
Hi all I have the following code to count up a number from a figure in my database. If I set the number to count up as a decimal for example 0.2 it breaks the script. I want it to instead count up to one decimal place eg if it is 0.2 then every second it will count up 0.2 -> 0.4 -> 0.6 etc. Obviously if this figure is just say 3 it should still count up 3 -> 6 -> 9 etc.
Cannot work out how to do this! Please help!
<script>
$(document).ready(function() {
timer = setInterval("countUP()", 1000);
});
var counter = 0;
var timer;
function countUP() {
var go = document.getElementsByClassName("standard");
for (var i = 0; i < go.length; i++) {
speed = parseInt(go[i].getAttribute('data-speed'));
go[i].setAttribute('data-counter', +go[i].getAttribute('data-counter') + speed);
go[i].innerHTML = numberWithCommas(go[i].getAttribute('data-counter'));
}
}
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;}
</script>
I then have this in my main html:
<div class="<?php echo $row["countuptype"]; ?>" data-speed="<?php echo $row["countupspeed"]; ?>">0</div>
Upvotes: 1
Views: 399
Reputation: 18032
Check this one:
$(document).ready(function() {
timer = setInterval("countUP()", 1000);
});
var counter = 0;
var timer;
function countUP() {
var go = document.getElementsByClassName("standard");
for (var i = 0; i < go.length; i++) {
speed = parseFloat(go[i].getAttribute('data-speed'));
go[i].setAttribute('data-counter', +go[i].getAttribute('data-counter') + speed);
go[i].innerHTML = numberWithCommas(parseFloat(go[i].getAttribute('data-counter')).toFixed(speed.countDecimals()));
}
}
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
Number.prototype.countDecimals = function () {
if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
return this.toString().split(".")[1].length || 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="standard" data-speed="0.2">0</div>
The speed should do parseFloat
instead of parseInt
to accept float values as speed.
And then you could get some strange numbers like 0.899999999 due to the float precision. To prevent from this I've used the toFloat passing the precision of the speed just before printing the value.
And the rest is just what you had.
Upvotes: 1