2

When the number reaches 1000 it adds the comma and becomes like so 1,000 although once it implements the ',' it then resets back to 12 where it should carry on.

Here is my jsFiddle: http://jsfiddle.net/m9cey/3/

var millisecs = 1000;
setInterval(function() {
    var $badge = $('#badge');
    var num = parseInt($badge.text())+11;
    $badge.text(num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}, millisecs);

Any help will be much appreciated.

Cheers

5
  • 1
    I would suggest separating the value and the output. That way you're not trying to parse text to a number and then converting it back. Store the value as data, and then output the stringified value to the DOM. jsfiddle.net/m9cey/10 Commented Aug 14, 2013 at 23:27
  • Why the + 11? What is that supposed to achieve? Commented Aug 14, 2013 at 23:27
  • Working as expected. parseInt will parse up to -- BUT NOT INCLUDING -- the comma. The documentation for parseInt will help you a lot. Commented Aug 14, 2013 at 23:30
  • Thanks for your input guys! The answer below helped! Commented Aug 14, 2013 at 23:33
  • I bet no one has ever had this question before. Commented Aug 15, 2013 at 0:04

3 Answers 3

2

Just posting my comment as an answer: http://jsfiddle.net/m9cey/10/

<span id="badge" data-value="900">900</span>

setInterval(function() {
    var $badge = $('#badge'),
        num = parseFloat($badge.data('value'));

    num += 11;

    $badge
        .data('value', num)
        .text(num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}, millisecs);
Sign up to request clarification or add additional context in comments.

Comments

1

The , in the value is causing parseInt to stop at it. So parseInt('1,xxx') will give you 1 then add eleven to it you get 12 .

Easiest solution remove the comma before parseInt

var num = parseInt($badge.text().replace(',', ''))+11;

http://jsfiddle.net/m9cey/9/

3 Comments

Thanks Musa this works perfect. Cheers for the fast response. Will tick asap.
If your numbers can get really big you need to replace globally
Going on from this topic, i'm trying to make it so that it goes up $11.43 per second. So ideally, I need to remove the .00 and include the 43 somehow? Any help would be great!
1

Have you heard of numerals.js?

var string = numeral(1000).format('0,0');
// '1,000'

1 Comment

Yup I had looked at that but then got lead onto something else!. Thanks though!

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.