简体   繁体   中英

Formatting decimal numbers in C#

How can I transform these numbers

Examples:

  1. 77.0227
  2. 0.0803
  3. 1.1567

Into these numbers respectively:

  1. 77,02
  2. 8,03
  3. 1,16

This all needs to be done with the same "formatting". These values come from a stored Procedure in SQL , and they are always different, but they need to be in the correct format. They are all Percent Values.

You can use the fixed-point ("F") format specifier to round to two digits:

decimal number = 77.0227m;
string result = number.ToString("F2");

If this doesn't give you the desired format(no commas but dots for example), then you have to pass the desired culture. Presuming you want spanish:

var spanishCulture = new CultureInfo("es-ES");
string result = number.ToString("F2", spanishCulture);

If you need commas as decimal separator you should need to specify the culture; like this:

string result = string.Format(new System.Globalization.CultureInfo("es-ES"), "{0:#,##0.00}", inputValue);

I'm supposing Spain's culture (Spanish language), so trying with that code.

See a running example in this fiddle .

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