Alex Rivera | Logout

Format numbers in JavaScript similar to C#

Asked 2009-07-01T09:53:58.093
77

Is there a simple way to format numbers in JavaScript, similar to the formatting methods available in C# (or VB.NET) via ToString("format_provider") or String.Format()?

Edit
Report

2 Answers

4

Firstly, converting an integer into string in JS is really simple:

// Start off with a number
var number = 42;
// Convert into a string by appending an empty (or whatever you like as a string) to it
var string = 42+'';
// No extra conversion is needed, even though you could actually do
var alsoString = number.toString();

If you have a number as a string and want it to be turned to an integer, you have to use the parseInt(string) for integers and parseFloat(string) for floats. Both of these functions then return the desired integer/float. Example:

// Start off with a float as a string
var stringFloat = '3.14';
// And an int as a string
var stringInt = '42';

// typeof stringInt  would give you 'string'

// Get the real float from the string
var realFloat = parseFloat(someFloat);
// Same for the int
var realInt = parseInt(stringInt);

// but typeof realInt  will now give you 'number'

What exactly are you trying to append etc, remains unclear to me from your question.

answered 2011-08-19T16:56:34.600
3

http://code.google.com/p/javascript-number-formatter/ :

  • Short, fast, flexible yet standalone. Only 75 lines including MIT license info, blank lines & comments.
  • Accept standard number formatting like #,##0.00 or with negation -000.####.
  • Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol.
  • Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid.
  • Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK.
  • Auto number rounding.
  • Simple interface, just supply mask & value like this: format( "0.0000", 3.141592)

UPDATE

As say Tomáš Zato here one line solution:

(666.0).toLocaleString()
numObj.toLocaleString([locales [, options]])

which described in ECMA-262 5.1 Edition:

and will work in future versions of browsers...

answered 2013-01-15T14:08:50.000

Your Answer