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 ?
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 %.
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.
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);
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With