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

Asked

Viewed 31,527 times

5

Hello. I need to make a simulator where a student enters the grade 1, the grade 2 and he calculates the average.

Note 1 is multiplied by 0,4 and Note 2 by 0,6.

Notes are decimal and only the second box 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 up to 5, 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 it rounds up.

Can someone help me in this matter?

Grateful.

2 answers

6

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

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));
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.