Makes writing numeric types as a formatted number much easier. Here it is set for double types:
void Main() { Console.WriteLine(1234.567.ToFixedDpFormat(2)); // => 1234.57 Console.WriteLine(1234.567.ToNumSigDigitsFormat(3)); // => 1.23E+03 Console.WriteLine(1234.567.ToCulturalFormat(2)); // => 1,234.57 Console.WriteLine(1234.567.ToCurrencyFormat()); // => £1,234.57 Console.WriteLine(1234d.ToFixedDpFormat(2)); // => 1234.00 Console.WriteLine(1.2340.ToNumSigDigitsFormat(3)); // => 1.23 Console.WriteLine(123445677.345234.ToCulturalFormat(2));// => 123,445,677.35 Console.WriteLine(1234345.567.ToCurrencyFormat()); // => £1,234,345.57 } namespace Common.Extensions.DoubleToStringFormatting { public static class DoubleToStringExtensions { public static string ToFixedDpFormat(this double number, int numDP = 0) { var res = number.ToString($"F{numDP}"); // ToFixedDpFormat(1234.567,2) (en - US) -> 1234.57 return res; } public static string ToNumSigDigitsFormat(this double number, int numSigDig = 3) { var res = number.ToString($"G{numSigDig}"); // ToNumSigDigitsFormat(123.4546) en-US -> 124.0 return res; } // Prettifies the string according to cultural aesthetics and the specified num of DP public static string ToCulturalFormat(this double number, int numDP = 2) { var res = number.ToString($"N{numDP}"); return res; } // Converts to a currency (using the default cultural currency sign) public static string ToCurrencyFormat(this double number, int numDP = 2) { var res = number.ToString($"C{numDP}"); // ToCurrencyFormat(123.456), en-US -> $123.46 return res; } } }Something similar can be used for float,decimal and int types as well.
No comments:
Post a Comment