How to round with 2 decimal places in javascript using a specific rule?

Hello. I need to make a simulator in which a student enters Grade 1, Grade 2 and he calculates the average.

Note 1 is multiplied by 0.4 and Note 2 by 0.6.

The notes are decimal and only the second Square after the comma is rounded.

Ex: 4,46-round to 4,5

The problem is that according to the criterion of the institution, if the second house is up to 4, it rounds down (4.94 - > 4.9) and if it is 5 up, it rounds up (4,95 -> 5,0).

I am using function

var  mediaFinal = Math.round(media_sem_arrend * 10) / 10;

In standard rounding functions, up to 5 it rounds down and from 6 it rounds up.

Can anyone help me in this matter?

Grateful.

Author: Vitor Alexandre Ferreira, 2016-02-23

2 answers

Use the function toFixed:

var n1 = 2.34;
var n2 = 2.35;

console.log(n1.toFixed(1)); //2.3
console.log(n2.toFixed(1)); //2.4

If you need to do more operations with the result, you need to convert it to float again using the function parseFloat, Once the function toFixed results in a string.

var n = 2.35;
var x = n.toFixed(1);
n = parseFloat(x);

console.log(n+1); //3.4
 6
Author: Filipe Moraes, 2016-02-23 14:19:58

You can create a rounding function using Math.floor. The function allows you to pass the number of decimal places that you want to round.

Follows the example below:

var arredonda = function(numero, casasDecimais) {
  casasDecimais = typeof casasDecimais !== 'undefined' ?  casasDecimais : 2;
  return +(Math.floor(numero + ('e+' + casasDecimais)) + ('e-' + casasDecimais));
};
 0
Author: Thiago Verney, 2016-02-23 18:18:09