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
  • 48,391
  • 102
  • 295
  • 498
  • 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

2 Answers2

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,872
  • 16
  • 24
-2

you can do something like :

var a= MyObject.MyProp,
number = a.substring(0,4) + ',' + a.substring(4,6) + ',' + a.substring(6)
Sina Fathieh
  • 1,663
  • 1
  • 19
  • 35