After an misinterpretation at my side, while reading the answer of the question How to get numbers to a specific decimal place ...
Summery of the Referenced Question:
Q: Feii Momo wants to know: How to round an amount of money to the nearest value within 0.05 steps.
A: The solution provided by Enigmativity is to multiply the value with 20 and round it and at least divided it by 20
Math.Round(value * 20.0m, 0) / 20.0m
... I came up with an more generic question:
Are there any practical advantages/disadvantages between these two approaches:
(I) var rValue = Math.Round(value * 10.0m , 0) / 10.0m; (II) var rValue = Math.Round(value, 1);
What I have done so far:
At first I looked at the Docs - System.Math.Round, but I could not found any hint. I also take a look at the the Reference Source - Decimal Round to see if there are any different executing branches, but so far it only comes up with:
public static Decimal Round(Decimal d, int decimals)
{
FCallRound (ref d, decimals);
return d;
}
and FCallRound
as:
private static extern void FCallRound(ref Decimal d, int decimals);
Unfortunately I did not found some code for FCallRound
.
After that I want to take it more practically and want to see if there are any performance difference, between rounding to 0 digits or to 1..n digits and "raced the horses".
At first I run these three function calls:
(1) var rValue = Math.Round(value, 0);
(2) var rValue = Math.Round(value, 1);
(3) var rValue = Math.Round(value, 12);
This shows me that for 1'000'000 iterations all three performed quiet equal (~70ms). And it seems there are no difference in the execution.
But just to check for any unexpected surprises, I compared these lines:
(1) var rValue = Math.Round(value, 1);
(2) var rValue = Math.Round(value * 10.0m, 0);
(3) var rValue = Math.Round(value * 10.0m, 0) / 10.0m;
As expected each multiplication increases the time ( ~ 70ms each).
So as expected in c# there are no performance benefits in Rounding and Dividing instead of Rounding to the wanted number of fractional digits.
So repeating my question:
Are there any practical advantages/disadvantages between these two approaches:
(I) var rValue = Math.Round(value * 10.0m , 0) / 10.0m; (II) var rValue = Math.Round(value, 1);