问题
To display a currency we do:
ToString("0.##")
For value 5.00
the output is:
5
For value 5.98
the output is:
5.98
For value 5.90
the output is:
5.9
I need the third case to come out with 2 decimal points, eg:
5.90
How can I do this without it affecting the other results?
回答1:
I know this doesn't give you a format that fixes the problem, but it's a simple solution to work around it.
(5.00).ToString("0.00").Replace(".00",""); // returns 5
(5.90).ToString("0.00").Replace(".00", ""); // returns 5.90
(5.99).ToString("0.00").Replace(".00", ""); // returns 5.99
回答2:
Try:
s.ToString("#,##0.00")
Or just:
s.ToString("C")
I know of no built-in way to expand out all two decimal places only when both are not zero. Would probably just use an if
statement for that.
int len = s.Length;
if (s[len - 2] == '0' && s[len - 1] == '0')
s = s.Left(len - 3);
回答3:
You could use an extension method, something like this:
public static string ToCurrencyString(this decimal d)
{
decimal t = Decimal.Truncate(d);
return d.Equals(t) ? d.ToString("0.##") : d.ToString("#, ##0.00")
}
回答4:
#
means if there is no number leave it empty 0 means put a 0 if there is no number
ToString("0.00")
回答5:
Not sure if I'm missing something, but can't you just do this:
decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
回答6:
Just use myDecimal.ToString("N")
,
With "N" parameter will transform decimal to string, and the number of decimals to show will be defined by your SO settings.
https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numberdecimaldigits(v=vs.110).aspx
来源:https://stackoverflow.com/questions/10437416/c-sharp-decimal-to-string-for-currency