martinezjc
martinezjc

Reputation: 3555

Math.round MidPointRounding.AwayFromZero in javascript

I wanted to get the same result in javascript from this line in c#:

round = Math.Round((17245.22 / 100), 2, MidpointRounding.AwayFromZero);
// Outputs: 172.45

I've tried this but no success:

var round = Math.round(value/100).toFixed(2);

Upvotes: 3

Views: 5466

Answers (1)

If you know that you are going to be diving by 100, you can just round first then divide:

var round = Math.round(value)/100; //still equals 172.45

However, if you don't know what you are going to be diving with, you can have this more generic form:

var round = Math.round(value/divisor*100)/100; //will always have exactly 2 decimal points

In this case the *100 will preserver 2 decimal points after the Math.round, and the /100 move move them back behind the decimal.

Upvotes: 5

Related Questions