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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With