tags:

views:

270

answers:

6

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));
}
+9  A: 

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.

Jon Skeet
+6  A: 

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(); 
Mehrdad Afshari
+15  A: 

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.

Jonas Elfström
+1 This is what the OP *really* wants to use. Sure, you can use as extension method, but there's really no point here...
Noldorin
+1 good way of answering
anishmarokey
+2  A: 

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)

MartinStettner
A: 

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())

e.g.: (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() );
    }
}
Johannes
Thanks for all answers. I used what looked like the simplest one - use the "F5" formating. Still, If I wanted to use a different way of formating my double.ToString, e.g. I would like to add a string at the end of the conversion ("2.345" -> "2.345 double"). Can I add another member to the double structer with different signiture, which is close to a totaly separate function but more similar to the original?
Eli
A: 

hi

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

nWorx