javascript – Round to two decimal places when necessary

Question:

I would like to round to two decimal places, only when necessary . Below are examples of inputs and outputs

Entry:

10
1.7777777
9.1

Exit:

10
1.78
9.1

How can I do this in JavaScript?

Fragment

 var valor = [ 10, 1.77777777, 9.1 ]; var resultado = valor.map(Math.round); console.log(resultado);

Question inspired by Round to at most 2 decimal places

Answer:

You can also use the toFixed () method, although it converts the number into a string and you should use the Number () function:

 var numero = 1.77777777; numero = Number(numero.toFixed(2)); console.log(numero); // Muestra 1.78

The bad thing is that it leaves 0 if the number does not contain a decimal or is less than the parameter passed to toFixed (). With this little function that problem is eliminated:

 function redondearDecimales(numero, decimales) { numeroRegexp = new RegExp('\\d\\.(\\d){' + decimales + ',}'); // Expresion regular para numeros con un cierto numero de decimales o mas if (numeroRegexp.test(numero)) { // Ya que el numero tiene el numero de decimales requeridos o mas, se realiza el redondeo return Number(numero.toFixed(decimales)); } else { return Number(numero.toFixed(decimales)) === 0 ? 0 : numero; // En valores muy bajos, se comprueba si el numero es 0 (con el redondeo deseado), si no lo es se devuelve el numero otra vez. } } console.log(redondearDecimales(1.777, 2)); // Devuelve 1.78 console.log(redondearDecimales(1, 2)); // Devuelve 1 console.log(redondearDecimales(1.7777, 3)); // Devuelve 1.778 console.log(redondearDecimales(0.0000007, 2)); // Devuelve 0 console.log(redondearDecimales(0.0000007, 7)); // Devuelve 7e-7 console.log(redondearDecimales(-1.3456, 2)); // Devuelve -1.35
Scroll to Top