ua741
ua741

Reputation: 1466

Keep rounding upto specified digit if non zero

I want to round Up decimal values upto two points. But for any number which is less than 0.01, I want to return 0.01.

RoundUp(0.146,2) should return 0.15

RoundUp(0.0003,2) should return 0.01

In C#, I am currently using Math.Round, with MidpointRounding.AwayFromZero parameter, but for

Math.Round(0.0003, 2, MidpointRounding.AwayFromZero);

it returns 0.

Is there any in built method in Math namespace, which I can use to get desired behavior?

Currently I am using this method

    private double GetRoundUpValue(double price, int roundUpto)
    {
        Debug.Assert(roundUpto == 2 || roundUpto == 3);
        var val = Math.Round(price, roundUpto, MidpointRounding.AwayFromZero);
        Double minValue = roundUpto == 2 ? 0.01 : 0.001;
        return val < minValue ? minValue : val;
    }

Upvotes: 1

Views: 135

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149050

But for any number which is less than 0.01, I want to return 0.01.

Then why not keep it simple and just use something like this:

Math.Max(Math.Round(0.0003, 2, MidpointRounding.AwayFromZero), 0.01);

Or if you need something more general, to round to n decimal places, use something like this:

private double GetRoundUpValue(double price, int places)
{
    var minValue = Math.Pow(0.1, places);
    return Math.Max(Math.Round(price, places, MidpointRounding.AwayFromZero), minValue);
}

Also note, that 'rounding away from zero' is not the same as 'rounding up' (for that, you can look at Math.Ceiling). So I'd recommend either changing the name of this method or it's body to be more clear about what's actually going on inside of it.

For example:

private double GetRoundUpValue(double price, int places)
{
    var scale = Math.Pow(10, places);
    return Math.Ceiling(price * scale) / scale;
}

Upvotes: 6

Related Questions