Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format numbers using JavaScript?

I want to format number using javascript as below:

10.00=10,00 
1,000.00=1.000,00
like image 767
Kanak Vaghela Avatar asked May 04 '11 11:05

Kanak Vaghela


People also ask

What are the methods of JavaScript number format?

Methods of JavaScript Number Format 1. toString () Method. This method returns the string and the parameter which can be passed can be either variable,... 2. toExponential () Method. This method returns a value which is a rounded number and exponential notation in the string. 3. toFixed () Method. ...

How to format numbers with commas in JavaScript?

The first way of formatting numbers with commas is using the toLocaleString () method. The JavaScript toLocaleString () method is used to convert the elements of the given array into a string, and these Strings are separated by a comma ",".

How do I format a number in Java?

You can use the toFixed () method to format the number with decimal points, and the toLocaleString () method to format the number with commas and Intl.NumberFormat () method to format the number with currency. You can also create your own custom function to format the number. This article covers all types of number conversion.

How to convert a number to a string in JavaScript?

Or you could use the sugar.js library, and the format method: format ( place = 0 , thousands = ',' , decimal = '.' ) Formats the number to a readable string. If place is undefined, will automatically determine the place. thousands is the character used for the thousands separator. decimal is the character used for the decimal point.


3 Answers

Every browser supports Number.prototype.toLocaleString(), a method intended to return a localized string from a number. However, the specification defines it as follows:

Produces a string value that represents the value of the Number formatted according to the conventions of the host environment's current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.

Implementation-dependant means that it's up to the vendor how the result will look, and results in interoperability issues.

Internet Explorer (IE 5.5 to IE 9) comes closest to what you want and formats the number in a currency style - thousands separator and fixed at 2 decimal places.

Firefox (2+) formats the number with a thousands separator and decimal places but only if applicable.

Opera, Chrome & Safari output the same as toString() -- no thousands separator, decimal place only if required.

Solution

I came up with the following code (based on an old answer of mine) to try and normalize the results to work like Internet Explorer's method:

(function (old) {
    var dec = 0.12 .toLocaleString().charAt(1),
        tho = dec === "." ? "," : ".";

    if (1000 .toLocaleString() !== "1,000.00") {
        Number.prototype.toLocaleString = function () {
           var neg = this < 0,
               f = this.toFixed(2).slice(+neg);

           return (neg ? "-" : "") 
                  + f.slice(0,-3).replace(/(?=(?!^)(?:\d{3})+(?!\d))/g, tho) 
                  + dec + f.slice(-2);
        }
    }
})(Number.prototype.toLocaleString);

This will use the browser's built-in localization if it's available, whilst gracefully degrading to the browser's default locale in other cases.

Working demo: http://jsfiddle.net/R4DKn/49/

like image 67
Andy E Avatar answered Sep 19 '22 02:09

Andy E


I know this solution using NumberFormat but it is necessary to convert the values to string. https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/NumberFormat

// Remove commas
number = "10,000.00".replace(/,/g, '');

// Create a NumberFormat type object
var formatter = new Intl.NumberFormat('de-DE', {
    minimumFractionDigits: 2
}); 

// Apply format
console.log(formatter.format(number));

output:10.000,00
like image 20
learango Avatar answered Sep 21 '22 02:09

learango


Javascript doesn't provide this functionality itself, but there are a number of third-party functions around which can do what you want.

Note, whichever method you use, you should be careful to only use the resulting string for display purposes -- it won't be a valid number value in Javascript after you've converted the decimal point to a comma.

The quickest solution I can offer is to use the number_format() function written by the phpJS people. They've implemented Javascript versions of a load of commonly-used PHP functions, including number_format(), and this function will do exactly what you want.

See the link here: http://phpjs.org/functions/number_format

I wouldn't bother about taking the whole phpJS library (a lot of it is of questionable value anyway), but just grab the 20-odd line function shown on the page linked above and paste it into your app.

If you want a more flexible solution, there are a number of JS functions around which simulate the printf() function from C. There is already a good question on SO covers this. See here: JavaScript equivalent to printf/string.format

Hope that helps.

like image 27
Spudley Avatar answered Sep 21 '22 02:09

Spudley