views:

2975

answers:

3

I'm trying to format various numbers on my page. These numbers either represent a price, a change in price, or a percentage. I know Javascript has functions to limit the number of decimal places, but is there any support for other types of formatting, such as grouping numbers with commas, controlling whether or not the +/- is shown, etc? Here's what I have so far:

var FORMATTER = {
    price       : function(value) { return '$' + value.toFixed(2); },
    pricePer    : function(value) { return (value * 100).toFixed(2) + '%'; },
    priceChg    : function(value) { return (value >= 0 ? '+' : '-') + '$' + Math.abs(value).toFixed(2); }
};

It works OK, but it'd like to add commas to the 'price' formatter, and you can see that there's a hack in the 'priceChg' formatter where I try to move the +/- sign in front of the '$' sign.

Basically, I'm hoping there is some library out there (jQuery is OK) that emulates Java's DecimalFormat class.

+2  A: 

No, there is no built-in support for number formatting, but googling will turn up loads of code snippets that will do this for you.

EDIT: I missed the last sentence of your post. Try http://code.google.com/p/jquery-utils/wiki/StringFormat for a jQuery solution.

ithcy
He's not asking for built-in support, he's asking for a library.
Daniel Lew
The post says "I know Javascript has functions to limit the number of decimal places, but is there any support for other types of formatting". Reads like he's asking about built-in support, if you don't read the whole post like me :)
ithcy
+4  A: 

There's the NUMBERFORMATTER jQuery plugin, details below:

http://plugins.jquery.com/project/numberformatter

From the above link:

This plugin is a NumberFormatter plugin. Number formatting is likely familiar to anyone who's worked with server-side code like Java or PHP and who has worked with internationalization.

EDIT: Replaced the link with a more direct one.

karim79
You should probably link to http://plugins.jquery.com/project/numberformatter instead.
Daniel Lew
You're right, thanks for that. Done.
karim79
Cool, this is exactly what I was looking for.
Outlaw Programmer
+1  A: 

Also try dojo.number which has built-in localization support. It is a much closer analog to Java's NumberFormat/DecimalFormat

peller