Mario
Mario

Reputation: 14780

Custom Math.Round

I want to round to 4 decimals and if anything after that is higher than 0 then round up to the next number.

Example:

 2.34121 ->  2.3413
50.58020 -> 50.5802
 4.49238 ->  4.4924
 0.00001 ->  0.0001

And Math.Round can round only from midpoint to up or down.

Upvotes: 0

Views: 633

Answers (3)

TurtlesAllTheWayDown
TurtlesAllTheWayDown

Reputation: 406

Just add 0.00004 before rounding.

Upvotes: 1

Infinity Challenger
Infinity Challenger

Reputation: 1140

public static class Extension
{
    public static double Convert(this double d)
    {
        var d1 = (int)(d * 10000);
        var d2 = (int)((d * 1000) * 10);
        if ((d1 - d2) != 0)
        {
            return Math.Round(d, 4) + 0.0001;
        }

        return Math.Round(d, 4);
    }
}

and then call 2.34121.Convert();

Upvotes: 1

Roman Koliada
Roman Koliada

Reputation: 5082

Try this:

double CustomRound(double x) => Math.Ceiling(x * 10000) / 10000;

Upvotes: 2

Related Questions