问题
I need to format a number with a specific format. I don't want to decide on the format with the regional settings of the computer so I'm trying:
string s = "219171"
string result = Convert.ToDouble(s).ToString("0,0.0") //219,171.0
string result = Convert.ToDouble(s).ToString("0.0,0") //219171.00
I want to display it as
219.171,00
Thank you
回答1:
Create a custom NumberFormatInfo instance and pass that in when calling ToString().
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberGroupSeparator = ".";
nfi.NumberDecimalSeparator = ",";
double s = 219171;
string result = s.ToString("N2", nfi);
NumberFormatInfo
belongs to System.Globalization
回答2:
You can specify the locale for which you want the number formatted in the Double.ToString(IFormatProvider provider)
overload. It you don't supply it, Thread.CurrentThread.CurrentUILocale
will be used. If you want it to be independant of the computer settings, you can use Double.ToString(CultureInfo.InvariantCulture)
.
If you want to completely customize the formatting (e. g. exactly x digit before/after the decimal seperator), look it up in a formatstring overview.
回答3:
The following should do the trick:
string result = (Convert.ToDouble(s) / 1000).ToString("##0.000\\,00");
Dividing 1000 changes the location of the decimal point. Each # or 0 is a digit.
Alternatively, you could use:
string result = Convert.ToDouble(s).ToString("000@000.00").Replace('.', ',').Replace('@', '.');
回答4:
I would probably do it like this:
// save parsing, ignoring current settings
double d = double.Parse(s, CultureInfo.InvariantCulture);
// whatever culture you actually want, assuming German
var culture = CultureInfo.GetCultureInfo("de");
string formatted = d.ToString(culture);
来源:https://stackoverflow.com/questions/5296806/double-tostring-for-formatting