Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Globalization;
- public class Program
- {
- public static void Main()
- {
- double val = 123456.789;
- string format = "#,.##0.00";
- string culture = "RU";
- var formattedValue = GetFormattedValue(val, format, culture);
- Console.WriteLine(formattedValue);
- }
- private static string GetFormattedValue(double? val, string format, string culture)
- {
- var formatString = format ?? "0.0";
- var signFormat =
- !formatString.StartsWith("#") && !formatString.StartsWith("+") ? "" :
- val <= 0 ? "" :
- "+";
- format = $"{signFormat}{formatString}";
- var ci = CultureInfo.GetCultureInfo(culture);
- var pos = format.IndexOf(',');
- if (pos != -1 && format.Length > pos + 1 && format[pos + 1] != '0')
- {
- var delimiter = format[pos + 1].ToString();
- ci = (CultureInfo) ci.Clone();
- ci.NumberFormat.CurrencyGroupSeparator = delimiter;
- ci.NumberFormat.PercentGroupSeparator = delimiter;
- ci.NumberFormat.NumberGroupSeparator = delimiter;
- format = format.Replace("," + delimiter, ",");
- }
- pos = format.IndexOf('.');
- if (pos != -1 && format.Length > pos + 1 && format[pos + 1] != '0')
- {
- var point = format[pos + 1].ToString();
- ci = (CultureInfo) ci.Clone();
- ci.NumberFormat.NumberDecimalSeparator = point;
- ci.NumberFormat.PercentDecimalSeparator = point;
- ci.NumberFormat.CurrencyDecimalSeparator = point;
- format = format.Replace("." + point, ".");
- }
- return val.Value.ToString(format, ci);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment