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?
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
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);
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")
}
#
means if there is no number leave it empty 0 means put a 0 if there is no number
ToString("0.00")
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);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.