Im working with an external payment system which uses a round down at exact midpoint, but round up if its anything more than that. I want to replicate the same in my application to match the value.
For example with two decimal point rounding, 150.415 is rounded to 150.41 and 150.4151 is rounded to 150.42. I am not entirely sure what this rounding mechanism is called.
To replicate the same behaviour in C#, I tried using Math.Round(amount, 2, MidpointRounding.AwayFromZero) and Math.Round(amount, 2, MidpointRounding.ToEven), but both rounds off the above number to 150.42
Trying to see what are my options here, including writing a custom function to do a similar rounding?
I think this is the logic that you need:
public static decimal DigitalRiverRounding(decimal value)
{
if (value < 0)
return Math.Floor(value * 100 + 0.5m) / 100m;
return Math.Ceiling(value * 100 - 0.5m) / 100m;
}
If you are certain no negative numbers are involved, you can of course remove the first two lines. I assumed for negative numbers the desired output is mirrored (-150.415 => -150.41, so they compensate appropriately).
Explanation assuming rounding with no decimals: as Ceiling converts 1.01 - 2.00 to 2, by doing -0.5 you are translating that into a logic that does 0.51 - 1.50 to 1, therefore 1.51 - 2.50 to 2, which is what you need.
In case you need to use this everywhere in your app, you may want to use an extension method instead, which needs a separate static helper class:
public static decimal ToDigitalRiverRounding(this decimal value)
{
if (value < 0)
return Math.Floor(value * 100 + 0.5m) / 100m;
return Math.Ceiling(value * 100 - 0.5m) / 100m;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With