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
  • 385
  • 3
  • 14
martinezjc
  • 3,415
  • 3
  • 21
  • 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
  • 19,209
  • 22
  • 79
  • 122
  • This saves my life, tanks a lot :) the first piece of bits got the price :), thanks a lot – martinezjc Feb 23 '15 at 21:39
  • Incorrect answer javascript Math.round rounds towards +∞; C# Math.Round((-17245.5 / 100), 2, MidpointRounding.AwayFromZero) = -172.46; js Math.round(-17245.5)/100 = -172.45 – Tomek Jun 21 '22 at 14:35