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)