简体   繁体   中英

Double.ToString for formatting

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

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

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 (eg exactly x digit before/after the decimal seperator), look it up in a formatstring overview .

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('@', '.');

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM