2

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?

KeenUser
  • 5,305
  • 14
  • 41
  • 62
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/226137/discussion-on-question-by-keenuser-c-midpoint-round-down-option-for-decimal). – Samuel Liew Dec 18 '20 at 15:20

2 Answers2

4

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;
}
Andrew
  • 7,602
  • 2
  • 34
  • 42
-3
#include <iostream>
#include <cmath>
using namespace std;
double roundN(double val, int len)
{
    double result;

    result = val * pow(10.0, len);
    result = static_cast<double>(static_cast<int>(result + 0.5));

    result = result * pow(10.0, -len);

    return result;
}

int main() {
    double a;
    cout<<"enter number"<<endl;
    cin>>a;
    a=roundN(a,2);
    std::cout << a;
    return 0;
}