1

Please review the Fiddle here

In the JS, I have some output for a number. This number is currently without a comma delimiter.

I would like to add a comma in the thousands place.

Here's my output snippet -

<input type="text" disabled="disabled" class="savings numbers" id="moneySaved">

Here's the JS that goes with that -

$("#moneySaved").val("$" +(resultNonNursing*402) + ( " in tuition costs")); //# of credits * cost per credit ($402)

I am trying to use the jQuery Number Formatter. I have this in the header -

$(document).ready(function() {
            $(".numbers").each(function() {
                $(this).format({format:"#,###", locale:"us"});
            });
        });

And I've added the numbers class to the html output -

<input type="text" disabled="disabled" class="savings numbers" id="moneySaved">

...but it is not working.

Can you provide some direction here?

3
  • What do you mean, it isn't working? Can you explain what you're getting as a result? I, and many other SO users, can't look at your fiddle, because it's restricted in work. Commented Jun 20, 2014 at 16:01
  • Well, I'm not getting the comma separator. The output is 1234 and I'm trying to accomplish 1,234, or 123,456,789, and 123. Commented Jun 20, 2014 at 16:02
  • Is it an ordering problem? You're applying the format to all numbers before you set the value. You don't need the .each by the way, you could just use $('.numbers').format(...). Commented Jun 20, 2014 at 16:04

1 Answer 1

2
Number.prototype.format = function(){
   return this.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
};

or if you don't like that

anumber.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
Sign up to request clarification or add additional context in comments.

5 Comments

I'd imagine this is the only case when he's using this format function call, so it's exactly what he'd want.
your second solution is a lot better
You can either add the Number.prototype and call format without any arguments (aka number.format();) or you can replace $(this).format({format:"#,###", locale:"us"}); with $(this).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
Here's an updated Fiddle. It's not working. I've added it as you suggested. Thoughts?
your function is on document ready and is not going to fire more than once, you should hook the function up to an event that makes sense, like onkeyup or onchange for the textbox.

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.