numberformat number money miles convert javascript jquery format numbers

javascript - money - number format html



Formatea nĂºmeros en JavaScript similares a C# (17)

Aquí hay algunas soluciones, todas pasan el conjunto de pruebas, conjunto de pruebas y punto de referencia incluido, si desea copiar y pegar para probar, pruebe This Gist .

Método 0 (RegExp)

Base en https://stackoverflow.com/a/14428340/1877620 , pero corrige si no hay punto decimal.

if (typeof Number.prototype.format === ''undefined'') { Number.prototype.format = function (precision) { if (!isFinite(this)) { return this.toString(); } var a = this.toFixed(precision).split(''.''); a[0] = a[0].replace(//d(?=(/d{3})+$)/g, ''$&,''); return a.join(''.''); } }

Método 1

if (typeof Number.prototype.format1 === ''undefined'') { Number.prototype.format1 = function (precision) { if (!isFinite(this)) { return this.toString(); } var a = this.toFixed(precision).split(''.''), // skip the ''-'' sign head = Number(this < 0); // skip the digits that''s before the first thousands separator head += (a[0].length - head) % 3 || 3; a[0] = a[0].slice(0, head) + a[0].slice(head).replace(//d{3}/g, '',$&''); return a.join(''.''); }; }

Método 2 (Split to Array)

if (typeof Number.prototype.format2 === ''undefined'') { Number.prototype.format2 = function (precision) { if (!isFinite(this)) { return this.toString(); } var a = this.toFixed(precision).split(''.''); a[0] = a[0] .split('''').reverse().join('''') .replace(//d{3}(?=/d)/g, ''$&,'') .split('''').reverse().join(''''); return a.join(''.''); }; }

Método 3 (Loop)

if (typeof Number.prototype.format3 === ''undefined'') { Number.prototype.format3 = function (precision) { if (!isFinite(this)) { return this.toString(); } var a = this.toFixed(precision).split(''''); a.push(''.''); var i = a.indexOf(''.'') - 3; while (i > 0 && a[i-1] !== ''-'') { a.splice(i, 0, '',''); i -= 3; } a.pop(); return a.join(''''); }; }

Ejemplo

console.log(''======== Demo ========'') var n = 0; for (var i=1; i<20; i++) { n = (n * 10) + (i % 10)/100; console.log(n.format(2), (-n).format(2)); }

Separador

Si queremos un separador de miles personalizado o un separador decimal, use replace ():

123456.78.format(2).replace('','', '' '').replace(''.'', '' '');

Banco de pruebas

function assertEqual(a, b) { if (a !== b) { throw a + '' !== '' + b; } } function test(format_function) { console.log(format_function); assertEqual(''NaN'', format_function.call(NaN, 0)) assertEqual(''Infinity'', format_function.call(Infinity, 0)) assertEqual(''-Infinity'', format_function.call(-Infinity, 0)) assertEqual(''0'', format_function.call(0, 0)) assertEqual(''0.00'', format_function.call(0, 2)) assertEqual(''1'', format_function.call(1, 0)) assertEqual(''-1'', format_function.call(-1, 0)) // decimal padding assertEqual(''1.00'', format_function.call(1, 2)) assertEqual(''-1.00'', format_function.call(-1, 2)) // decimal rounding assertEqual(''0.12'', format_function.call(0.123456, 2)) assertEqual(''0.1235'', format_function.call(0.123456, 4)) assertEqual(''-0.12'', format_function.call(-0.123456, 2)) assertEqual(''-0.1235'', format_function.call(-0.123456, 4)) // thousands separator assertEqual(''1,234'', format_function.call(1234.123456, 0)) assertEqual(''12,345'', format_function.call(12345.123456, 0)) assertEqual(''123,456'', format_function.call(123456.123456, 0)) assertEqual(''1,234,567'', format_function.call(1234567.123456, 0)) assertEqual(''12,345,678'', format_function.call(12345678.123456, 0)) assertEqual(''123,456,789'', format_function.call(123456789.123456, 0)) assertEqual(''-1,234'', format_function.call(-1234.123456, 0)) assertEqual(''-12,345'', format_function.call(-12345.123456, 0)) assertEqual(''-123,456'', format_function.call(-123456.123456, 0)) assertEqual(''-1,234,567'', format_function.call(-1234567.123456, 0)) assertEqual(''-12,345,678'', format_function.call(-12345678.123456, 0)) assertEqual(''-123,456,789'', format_function.call(-123456789.123456, 0)) // thousands separator and decimal assertEqual(''1,234.12'', format_function.call(1234.123456, 2)) assertEqual(''12,345.12'', format_function.call(12345.123456, 2)) assertEqual(''123,456.12'', format_function.call(123456.123456, 2)) assertEqual(''1,234,567.12'', format_function.call(1234567.123456, 2)) assertEqual(''12,345,678.12'', format_function.call(12345678.123456, 2)) assertEqual(''123,456,789.12'', format_function.call(123456789.123456, 2)) assertEqual(''-1,234.12'', format_function.call(-1234.123456, 2)) assertEqual(''-12,345.12'', format_function.call(-12345.123456, 2)) assertEqual(''-123,456.12'', format_function.call(-123456.123456, 2)) assertEqual(''-1,234,567.12'', format_function.call(-1234567.123456, 2)) assertEqual(''-12,345,678.12'', format_function.call(-12345678.123456, 2)) assertEqual(''-123,456,789.12'', format_function.call(-123456789.123456, 2)) } console.log(''======== Testing ========''); test(Number.prototype.format); test(Number.prototype.format1); test(Number.prototype.format2); test(Number.prototype.format3);

Punto de referencia

function benchmark(f) { var start = new Date().getTime(); f(); return new Date().getTime() - start; } function benchmark_format(f) { console.log(f); time = benchmark(function () { for (var i = 0; i < 100000; i++) { f.call(123456789, 0); f.call(123456789, 2); } }); console.log(time.format(0) + ''ms''); } async = []; function next() { setTimeout(function () { f = async.shift(); f && f(); next(); }, 10); } console.log(''======== Benchmark ========''); async.push(function () { benchmark_format(Number.prototype.format); }); async.push(function () { benchmark_format(Number.prototype.format1); }); async.push(function () { benchmark_format(Number.prototype.format2); }); async.push(function () { benchmark_format(Number.prototype.format3); }); next();

¿Existe alguna forma sencilla de formatear números en JavaScript, de forma similar a los métodos de formato disponibles en C # (o VB.NET) a través de ToString("format_provider") o String.Format() ?


Aquí hay otra versión:

$.fn.digits = function () { return this.each(function () { var value = $(this).text(); var decimal = ""; if (value) { var pos = value.indexOf("."); if (pos >= 0) { decimal = value.substring(pos); value = value.substring(0, pos); } if (value) { value = value.replace(/(/d)(?=(/d/d/d)+(?!/d))/g, "$1,"); if (!String.isNullOrEmpty(decimal)) value = (value + decimal); $(this).text(value); } } else { value = $(this).val() if (value) { var pos = value.indexOf("."); if (pos >= 0) { decimal = value.substring(pos); value = value.substring(0, pos); } if (value) { value = value.replace(/(/d)(?=(/d/d/d)+(?!/d))/g, "$1,"); if (!String.isNullOrEmpty(decimal)) value = (value + decimal); $(this).val(value); } } } }) };


Aquí hay una función JS simple para agregar comas a un número entero en formato de cadena. Manejará números enteros o números decimales. Puede pasarlo ya sea un número o una cadena. Obviamente devuelve una cadena.

function addCommas(str) { var parts = (str + "").split("."), main = parts[0], len = main.length, output = "", first = main.charAt(0), i; if (first === ''-'') { main = main.slice(1); len = main.length; } else { first = ""; } i = len - 1; while(i >= 0) { output = main.charAt(i) + output; if ((len - i) % 3 === 0 && i > 0) { output = "," + output; } --i; } // put sign back output = first + output; // put decimal part back if (parts.length > 1) { output += "." + parts[1]; } return output; }

Aquí hay un conjunto de casos de prueba: http://jsfiddle.net/jfriend00/6y57j/

Puede ver que se usa en este jsFiddle anterior: http://jsfiddle.net/jfriend00/sMnjT/ . Puede encontrar funciones que también manejarán números decimales con una simple búsqueda en Google de "comas de javascript".

La conversión de un número a una cadena se puede hacer de muchas maneras. Lo más fácil es simplemente agregarlo a una cadena:

var myNumber = 3; var myStr = "" + myNumber; // "3"

Dentro, el contexto de tu jsFiddle, obtendrías comas en el contador cambiando esta línea:

jTarget.text(current);

a esto:

jTarget.text(addCommas(current));

Puedes verlo trabajando aquí: http://jsfiddle.net/jfriend00/CbjSX/


En caso de que desee formatear el número para la vista en lugar de para el cálculo, puede usar esto

function numberFormat( number ){ var digitCount = (number+"").length; var formatedNumber = number+""; var ind = digitCount%3 || 3; var temparr = formatedNumber.split(''''); if( digitCount > 3 && digitCount <= 6 ){ temparr.splice(ind,0,'',''); formatedNumber = temparr.join(''''); }else if (digitCount >= 7 && digitCount <= 15) { var temparr2 = temparr.slice(0, ind); temparr2.push('',''); temparr2.push(temparr[ind]); temparr2.push(temparr[ind + 1]); // temparr2.push( temparr[ind + 2] ); if (digitCount >= 7 && digitCount <= 9) { temparr2.push(" million"); } else if (digitCount >= 10 && digitCount <= 12) { temparr2.push(" billion"); } else if (digitCount >= 13 && digitCount <= 15) { temparr2.push(" trillion"); } formatedNumber = temparr2.join(''''); } return formatedNumber; }

Entrada: {Entero} Número

Salidas: {String} Number

22,870 => si el número 22870

22,87 millones => si número 2287xxxx (x puede ser lo que sea)

22,87 billones => si el número 2287xxxxxxx

22,87 billones => si el número 2287xxxxxxxxxx

Usted obtiene la idea


En primer lugar, convertir un entero en cadena en JS es realmente 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();

Si tiene un número como una cadena y desea que se convierta en un número entero, debe usar parseInt(string) para enteros y parseFloat(string) para flotantes. Ambas funciones devuelven el número entero / flotante deseado. Ejemplo:

// 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''

¿Qué es exactamente lo que está tratando de agregar, etc, sigue sin estar claro para mí a partir de su pregunta.


Escribí una función simple (¡no es necesario otro complemento de jQuery!) Que convierte un número en una cadena separada por decimales o una cadena vacía si el número no era un número para empezar:

function format(x) { return isNaN(x)?"":x.toString().replace(//B(?=(/d{3})+(?!/d))/g, ","); }

format(578999); resultados en 578,999

format(10); resultados en 10

si desea tener un punto decimal en lugar de una coma, simplemente reemplace la coma en el código con un punto decimal.

Uno de los comentarios indicaba correctamente que esto solo funciona para enteros, con algunas adaptaciones pequeñas también puedes hacer que funcione para puntos flotantes:

function format(x) { if(isNaN(x))return ""; n= x.toString().split(''.''); return n[0].replace(//B(?=(/d{3})+(?!/d))/g, ",")+(n.length>1?"."+n[1]:""); }


Hice una función simple, tal vez alguien puede usarla

function secsToTime(secs){ function format(number){ if(number===0){ return ''00''; }else { if (number < 10) { return ''0'' + number } else{ return ''''+number; } } } var minutes = Math.floor(secs/60)%60; var hours = Math.floor(secs/(60*60))%24; var days = Math.floor(secs/(60*60*24)); var seconds = Math.floor(secs)%60; return (days>0? days+"d " : "")+format(hours)+'':''+format(minutes)+'':''+format(seconds); }

esto puede generar los siguientes resultados:

  • 5d 02:53:39
  • 4d 22:15:16
  • 03:01:05
  • 00:00:00

Para obtener un decimal con 2 números después de la coma, puedes usar:

function nformat(a) { var b = parseInt(parseFloat(a)*100)/100; return b.toFixed(2); }


Para seguir la respuesta de jfriend00 (no tengo suficientes puntos para comentar) he extendido su respuesta a lo siguiente:

function log(args) { var str = ""; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] === "object") { str += JSON.stringify(arguments[i]); } else { str += arguments[i]; } } var div = document.createElement("div"); div.innerHTML = str; document.body.appendChild(div); } Number.prototype.addCommas = function (str) { if (str === undefined) { str = this; } var parts = (str + "").split("."), main = parts[0], len = main.length, output = "", first = main.charAt(0), i; if (first === ''-'') { main = main.slice(1); len = main.length; } else { first = ""; } i = len - 1; while(i >= 0) { output = main.charAt(i) + output; if ((len - i) % 3 === 0 && i > 0) { output = "," + output; } --i; } // put sign back output = first + output; // put decimal part back if (parts.length > 1) { output += "." + parts[1]; } return output; } var testCases = [ 1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789, -1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1 ]; for (var i = 0; i < testCases.length; i++) { log(testCases[i].addCommas()); } /*for (var i = 0; i < testCases.length; i++) { log(Number.addCommas(testCases[i])); }*/


Por ejemplo:

var flt = ''5.99''; var nt = ''6''; var rflt = parseFloat(flt); var rnt = parseInt(nt);



Puedo sugerir numbro para el formato basado en la configuración regional y number-format.js para el caso general. Una combinación de los dos dependiendo del caso de uso puede ayudar.


Sí, definitivamente hay una manera de formatear los números correctamente en javascript, por ejemplo:

var val=2489.8237 val.toFixed(3) //returns 2489.824 (round up) val.toFixed(2) //returns 2489.82 val.toFixed(7) //returns 2489.8237000 (padding)

Con el uso de nombre de variable. aFija .

Y hay otra función toPrecision() . Para más detalles también puede visitar

http://raovishal.blogspot.com/2012/01/number-format-in-javascript.html


Si no quiere usar jQuery, eche un vistazo a Numeral.js


Usando JQuery .

$(document).ready(function() { //Only number and one dot function onlyDecimal(element, decimals) { $(element).keypress(function(event) { num = $(this).val() ; num = isNaN(num) || num === '''' || num === null ? 0.00 : num ; if ((event.which != 46 || $(this).val().indexOf(''.'') != -1) && (event.which < 48 || event.which > 57)) { event.preventDefault(); } if($(this).val() == parseFloat(num).toFixed(decimals)) { event.preventDefault(); } }); } onlyDecimal("#TextBox1", 3) ; });


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

  • Corto, rápido, flexible pero independiente. Solo 75 líneas, incluida la información de licencia de MIT, líneas en blanco y comentarios.
  • Acepte el formato de número estándar como #, ## 0.00 o con negation -000. ####.
  • Acepte cualquier formato de país como ### 0,00, #, ###. ##, # ''###. ## o cualquier tipo de símbolo de no numeración.
  • Acepta cualquier cantidad de agrupación de dígitos. #, ##, # 0.000 o #, ### 0. ## son todos válidos.
  • Acepte cualquier formato redundante / a prueba de tontos. ##, ###, ##. # o 0 #, # 00 #. ### 0 # están bien.
  • Redondeo automático de números.
  • Interfaz simple, solo proporciona máscara y valor como este: formato ("0.0000", 3.141592)

ACTUALIZAR

Como dice Tomáš Zato aquí una solución de línea:

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

que se describe en ECMA-262 5.1 Edition:

y funcionará en futuras versiones de navegadores ...