简体   繁体   中英

override .ToString()

I would like to override the .ToString() function so that whenever I get a double it outputs only 5 digits after the decimal point.

How do I reffer to the object the .ToString is working on, inside the override function? In other words what shell I put instead of the XXX in the following code?

public override string ToString()
{
    if (XXX.GetType().Name == "Double")
        return (Math.Round(XXX, 5));
}

Why not just use the built-in formatting?

var pi = 3.14159265m;
Console.WriteLine(pi.ToString("N5"));
-> "3.14159"

For reference I like the .NET Format String Quick Reference by John Sheehan.

You can't override a method for a different type - basically you can't stop double.ToString doing what it does. You can, however, write a method which takes a double and formats it appropriately.

As Jon pointed out, you can't override Double.ToString . You can create an extension method for double type that helps you do this:

public static class DoubleExtensions {
   public static string ToStringWith5Digits(this double x) { ... }
}

and use it like:

double d = 10;
string x = d.ToStringWith5Digits(); 

You can pass a format argument to Double.ToString() specifying the number of digits:

double x = 5.12345667;
string s = x.ToString("F5"); // s="5.12345", x.ToString("#.#####") also works

You can't override the ToString() function for doubles (it is a member function of struct Double)

What class does your ToString() function belong to? Typically you have private variable inside the class you use. (But could also be a combination of variables to build a ToString())

eg: (pseudo code this is)

class MyClass
{
  private double dd;
  private string prefix = "MyDouble:";
  ...
  ...
    public override string ToString()
    {
        if (dd.GetType().Name == "Double")
        return ( prefix + Math.Round(dd, 5).ToString() );
    }
}

you cannot override, but you could a extension method

public static string ToRoundString(this double doubleValue)
{
   return Math.Round(doubleValue, 5).ToString();
}

usage

public void TestMethod()
{
   double greatValue = 3;
   string newString = greatVale.ToRoundString();
}

cheers

While the "F5" or "#.#####" solves the specifics of the original post, as the title is rather broader ("override .ToString()"), I thought I'd add that you can also create an extension method which overloads ToString() .

So, for example, an extension method of:

    public static string ToString(this double value, int roundTo, string roundSuffix)
    {
        string rounded = value.ToString($"#.{new String('#', roundTo)}");
        if (rounded != value.ToString())
        {
            rounded = $"{rounded}{roundSuffix}";
        }
        return rounded;
    }

Would produce "5.25 was rounded" if passed

double d = 5.2514;
string formatted = d.ToString(2, " was rounded");

or "5.2" if passed

double d = 5.2;
string formatted = d.ToString(2, " was rounded");

(just on the off chance there's some weird use case where someone wants to do something like that!)

You shouldn't attempt to override ToString() with a method that has the same signature as one of the built-in ToString() overloads however, as while the IDE will see it, it will never call the extension method (see How to call extension method which has the same name as an existing method? for details)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM