Give different numerical format with JavaScript

4

Is it possible to perform the number format that is done in php but in javascript? I found that it could be with valor.toFixed(); but it does not. Does anyone know another way to do it? Something like 46786.62 convert it to 46,786.62

    
asked by Santiago Muñoz 12.08.2016 в 19:23
source

2 answers

5

You can use the toLocaleString() function, which convert a number to a string giving it the specified local format (and if you do not specify any, it will format the number to the location that has the default browser).

The format you can pass as the first parameter and must conform to the specified format here .

  

NOTE - A problem with this function: Safari does not support it in any of its versions, and it does not work in IE versions prior to 11.

Here is an example:

var number = 46786.62;

// sin parámetros será el formato por defecto de tu navegador
console.log("Formato automático --- " + number.toLocaleString());

// le puedes pasar un código de locale específico
console.log("Formato en EE.UU. ---- " + number.toLocaleString("en-US"));
console.log("Formato de España ---- " + number.toLocaleString("es-ES"));
    
answered by 12.08.2016 / 23:21
source
0

.toFixed(2) what it does as such is add 00 after the whole number or after a point.

Now what you are looking to do there is no native method in javascript that does it. you would have to design a function that does it, I leave you the function you are looking for:

var valor = 10000.34
console.log(addCommas(valor));
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
    
answered by 12.08.2016 в 20:01