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

3

Hello. I need to do a simulator in which a student inserts note 1, note 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 house after the comma is rounded.

Ex: 4.46 - round to 4.5

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

I'm using the function

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

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

Can anyone help me with this?

Thank you.

    
asked by anonymous 23.02.2016 / 14:56

2 answers

1

Use the toFixed function:

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 parseFloat ", since the toFixed results in a string .

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

console.log(n+1); //3.4
    
23.02.2016 / 15:13
0

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

Follow the example below:

var arredonda = function(numero, casasDecimais) {
  casasDecimais = typeof casasDecimais !== 'undefined' ?  casasDecimais : 2;
  return +(Math.floor(numero + ('e+' + casasDecimais)) + ('e-' + casasDecimais));
};
    
23.02.2016 / 19:18