десятичные разряды переменных в форматах строк .Net?

Фиксировать десятичные разряды легко

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

дает

654.3

Как мне указать количество десятичных знаков в качестве параметра как можно в C? Итак,

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

дает

654.32

Я не могу найти, чем заменить?

18
задан GazTheDestroyer 18 August 2011 в 14:15
поделиться

1 ответ

Я использую , интерполированная строка приближается подобный ответу Wolfgang, но немного более компактный и читаемый (по моему скромному мнению):

using System.Globalization;
using NF = NumberFormatInfo;

...

decimal size = 123.456789;  
string unit = "MB";
int fracDigs = 3;

// Some may consider this example a bit verbose, but you have the text, 
// value, and format spec in close proximity of each other. Also, I believe 
// that this inline, natural reading order representation allows for easier 
// readability/scanning. There is no need to correlate formats, indexes, and
// params to figure out which values go where in the format string.
string s = $"size:{size.ToString("N",new NF{NumberDecimalDigits=fracDigs})} {unit}";
0
ответ дан 30 November 2019 в 08:57
поделиться
Другие вопросы по тегам:

Похожие вопросы: