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);
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);
Share
Improve this question
edited Aug 7, 2021 at 12:06
Chris Akridge
3953 silver badges14 bronze badges
asked Feb 23, 2015 at 21:17
martinezjcmartinezjc
3,5653 gold badges24 silver badges29 bronze badges
2
-
1
simply don't round, since you fix anyway:
(17245.22/100).toFixed(2)==172.45;
– dandavis Commented Feb 23, 2015 at 21:40 - I Believe that my answer also address this issue: stackoverflow./a/60729374/6844481 – Shahar Shokrani Commented Mar 17, 2020 at 20:04
1 Answer
Reset to default 5If 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.