[C#] decimal 转换为 string

可以使用 toString:

public static string ReadExchangeRate(string fromCurrencyCode, string toCurrencyCode)
{
    BaseCurrency = fromCurrencyCode;
    decimal conversion = PreformConversion(toCurrencyCode);
    return "1 " + toCurrencyCode + " = " + conversion.ToString() + " " + fromCurrencyCode; //$"1 {toCurrencyCode} = {conversion}{fromCurrencyCode} ";
}

输出结果:

The current Rand / Dollar exchange rate is:
1 USD = 16.3040 ZAR

如果是C# 6.0 可以用注释的语句 $"1 {toCurrencyCode} = {conversion}{fromCurrencyCode} ",非6.0不支持。

也可以使用String.Format连接string和decimal:

String.Format("1 {0} = {1} {2} ", toCurrencyCode, conversion, fromCurrencyCode);

这里出现了花括号,如果表达式本身带有花括号,就用双花括号代替,例如,如果要表达{16,3040}, 那么表达式应改为: $"{{{conversion}}}";


[1] https://stackoverflow.com/questions/8125492/converting-decimal-to-string-with-non-default-format/8125511

你可能感兴趣的:(Other)