Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable decimal places in .Net string formatters?

Tags:

Fixed decimal places is easy

String.Format("{0:F1}", 654.321); 

gives

654.3 

How do I feed the number of decimal places in as a parameter like you can in C? So

String.Format("{0:F?}", 654.321, 2); 

gives

654.32 

I can't find what should replace the ?

like image 327
GazTheDestroyer Avatar asked Aug 18 '11 14:08

GazTheDestroyer


People also ask

How do you format a string to show two decimal places?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

What is %s in string format?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.


2 Answers

The string to format doesn't have to be a constant.

int numberOfDecimalPlaces = 2; string formatString = String.Concat("{0:F", numberOfDecimalPlaces, "}"); String.Format(formatString, 654.321); 
like image 118
Chris Shouts Avatar answered Sep 30 '22 01:09

Chris Shouts


Use NumberFormatInfo:

Console.WriteLine(string.Format(new NumberFormatInfo() { NumberDecimalDigits = 2 }, "{0:F}", new decimal(1234.567))); Console.WriteLine(string.Format(new NumberFormatInfo() { NumberDecimalDigits = 7 }, "{0:F}", new decimal(1234.5))); 
like image 39
Wolfgang Grinfeld Avatar answered Sep 30 '22 02:09

Wolfgang Grinfeld