Although "F5" or "#. #####" decides the specifics of the original post, as the title is wider ("override.ToString ()"), I thought I'd add that you can also create an extension method that overloads ToString() .
So, for example, the extension method:
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; }
Will 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 by chance there is some strange case when someone wants to do something like that!)
However, you should not try to override the ToString() method with a method that has the same signature as one of the built-in ToString() overloads, because while the IDE sees it, it will never call the extension method (see How to call the extension method, which has the same name as the existing method? for details)
d219
source share