Rounding to midpoint of decimal place using ToString only

671 Views Asked by At

I know that C# has some options to format decimal numbers with some extended logic in the ToString() method, as e.g.

double d1 = 1.3333;
double d2 = 1.6666;
string d1Str = d1.ToString("#0.00"); // 1.33
string d2Str = d2.ToString("#0.00"); // 1.67

That's great, my number is rounded to the second decimal. But what if I wanted to round to a step of 0.05 instead of 0.01? Is there a way to use the ToString() method in a similar way to round the value not to a given step-size (e.g. 0.05)?

Note: I know I could do something like this:

(Math.Round(1.33333*20)/20).ToString();

but the question is about getting this result using ToString() only.

1

There are 1 best solutions below

0
d219 On

Is it possible for you to create an extension overload for ToString() for these components?

If so you could write something like:

public static class DoubleStaticExtension
{
    public static string ToString(this double value, string format, int decimalToRoundHalfwayAt)
    {
        int modifier = 2 * (int)Math.Pow(10, decimalToRoundHalfwayAt -1 );
        return (Math.Round(value * modifier, MidpointRounding.AwayFromZero) / modifier).ToString(format);
    }
}

Calling that with

        double d = 9.333333;
        string result = d.ToString("#0.00", 2);

Would give a result of 9.35

And

    double d = 9.333333;
    string result = d.ToString("#0.00", 1);

Would give a result of 9.50