1

I have an object MyObject that contains a property MyProp that is sometimes numeric. At the moment, I'm showing the number as text like this:

$('#MyDiv').text(MyObject.MyProp);

I want to add formatting to this number. I can check it's numeric but I'm wondering how to do the number formatting.

if ($.isNumeric(MyObject.MyProp) === false) {

   $('#MyDiv').text(MyObject.MyProp);

} else {

   var PrettyNumber = MakePrettyNumber(MyObject.MyProp);
   $('#MyDiv').text(PrettyNumber);
}

I'm thinking about looping through the length of the number string and adding commas to separate thousands and add a dot for decimal. Is there a better way? One that doesn't require a plug-in?

Thanks.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • There are no native facilities in any standard JavaScript runtime for doing what you're describing. You'll have to write your own code or use some other library. – Pointy May 27 '12 at 13:04

1 Answers1

0
function MakePrettyNumber(x) {
  var res = x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  res = res.replace(/^([^\.]*)$/g, "$1.000");
  return res;
}

See here for details: How to print a number with commas as thousands separators in JavaScript

Community
  • 1
  • 1
Mandar Limaye
  • 1,900
  • 16
  • 24