3

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);
Chris Akridge
  • 355
  • 5
  • 13
martinezjc
  • 3,165
  • 3
  • 19
  • 29

1 Answers1

5

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.

David says Reinstate Monica
  • 18,041
  • 20
  • 73
  • 118