Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

80
Vistas
JS Rounding 3 decimal points to 2 decimal
Math.round(num * 100) / 100

Case 1:

15.625 * 19 = 296.875

When we apply the code above, the final result is 296.88 which is correct.

var test = 15.625 * 19;
test = Math.round(test * 100) / 100;
console.log( test ); // Return 296.88 (Correct)

Case 2:

15.225 * 19 = 289.275

When we apply the code above, the final result is 289.27 which is not correct.

var test = 15.225 * 19;
test = Math.round(test * 100) / 100;
console.log( test ); // Return 289.27 (Not correct)

Hence, I tried to breakdown and found out that:

289.275 * 100 = 28927.499999999996
Math.round(28927.499999999996) = 28927
Then, 28927/100 = 289.27

The suppose to be 0.5 turned into 0.499999999996 after multiply by 100

(^ This is the part I'm stuck and not sure how to proceed)

For temporary usage, I did something like this as below:

var compiledPrice = 289.275;
console.log( 'compiledPrice1 : ' + compiledPrice );
// 289.275

compiledPrice = compiledPrice * 10;
console.log( 'compiledPrice2 : ' + compiledPrice );
// 2892.75

compiledPrice = compiledPrice.toFixed(1);
console.log( 'compiledPrice3 : ' + compiledPrice );
// 2892.8

compiledPrice = compiledPrice / 10;
console.log( 'compiledPrice4 : ' + compiledPrice );
// 289.28000000000003

compiledPrice = compiledPrice.toFixed(2);
console.log( 'compiledPrice5 : ' + compiledPrice );
// 289.28

I'm not sure is this the proper way to solve this issue, I hope somebody would able to shed some light to me please.

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos