JavaScript mostrando un flotador a 2 decimales


Quería mostrar un número a 2 decimales.

Pensé que podría usar toPrecision(2) en JavaScript .

Sin embargo, si el número es 0.05, obtengo 0.0500. Prefiero que siga igual.

Véalo en JSbin.

¿Cuál es la mejor manera de hacer esto?

Puedo pensar en codificar algunas soluciones, pero me imagino (espero) que algo como esto está integrado?

Author: mskfisher, 2010-07-02

7 answers

float_num.toFixed(2);

Nota:toFixed() redondeará o rellenará con ceros si es necesario para cumplir con la longitud especificada.

 390
Author: Jason McCreary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-23 12:50:56

Puedes hacerlo con la función toFixed, pero es con errores en IE. Si quieres una solución confiable, mira mi respuesta aquí.

 47
Author: Elias Zamaria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:51

Intente toFixed en lugar de toPrecision.

 15
Author: casablanca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-02 03:24:24

No sé cómo llegué a esta pregunta, pero incluso si han pasado muchos años desde que se me preguntó, me gustaría agregar un método rápido y simple que sigo y nunca me ha decepcionado:

var num = responce_from_a_function_or_something();
var fixed_num = parseFloat(num).toFixed( 2 );
 5
Author: panos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-13 10:49:16

function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); }

Round (1.005, 2); / / return 1.01

Round (1.004, 2); // devuelve 1 en lugar de 1.00

La respuesta está siguiendo este enlace: http://www.jacklmoore.com/notes/rounding-in-javascript /

 1
Author: Huy Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-28 04:51:01

El método toFixed() formatea un número usando notación de punto fijo.

Y aquí está la sintaxis

numObj.toFixed([digits])

El argumento Digits es opcional y por defecto es 0. Y el tipo de retorno es cadena no número. Pero puede convertirlo en número usando

numObj.toFixed([digits]) * 1

También puede lanza excepciones como TypeError, RangeError

Aquí está el completo detalle y la compatibilidad en el navegador.

 1
Author: Sunil Garg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-09 08:52:13

He hecho esta función. Funciona bien pero devuelve cadena.

function show_float_val(val,upto = 2){
  var val = parseFloat(val);
  return val.toFixed(upto);
}
 0
Author: Syed Nurul Islam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-22 07:25:18