40
A
回答
76
屬性可以返回任何他們想要的東西,但它需要返回正確的類型。
private decimal _amount;
public string FormattedAmount
{
get { return string.Format("{0:C}", _amount); }
}
問題被問到......如果它是一個可爲空的小數。
private decimal? _amount;
public string FormattedAmount
{
get
{
return _amount == null ? "null" : string.Format("{0:C}", _amount.Value);
}
}
0
十進制類型不能包含格式信息。你可以創建另一個屬性,比如FormattedProperty
,它是一個你想要的字符串類型。
4
可以使用的String.Format,看到代碼[通過How-to Geek]:
decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
// Output: $1,921.39
參見:
26
下面也會起作用,但不能放入小數屬性的吸氣劑。小數屬性的getter只能返回小數點,格式不適用。
decimal moneyvalue = 1921.39m;
string currencyValue = moneyvalue.ToString("C");
1
您返回的格式將受到您聲明的返回類型的限制。所以是的,你可以聲明該屬性爲一個字符串,並返回格式化值的東西。在「獲取」你可以把任何你需要的數據檢索代碼。因此,如果您需要訪問某些數值,只需將您的返回語句設爲:
private decimal _myDecimalValue = 15.78m;
public string MyFormattedValue
{
get { return _myDecimalValue.ToString("c"); }
private set; //makes this a 'read only' property.
}
6
試試這個;
string.Format(new CultureInfo("en-SG", false), "{0:c0}", 123423.083234);
它會將123423.083234轉換爲$ 1,23,423格式。
1
現在可以使用串內插和表達濃郁性能在C#6
private decimal _amount;
public string FormattedAmount => $"{_amount:C}";
2
可以創建一個擴展方法。我認爲這是一個很好的做法,因爲無論瀏覽器設置如何,您都可能需要鎖定貨幣顯示。例如,您可能希望顯示$ 5,000.00始終,而不是5 000,00 $ (#CanadaProblems)
public static class DecimalExtensions
{
public static string ToCurrency(this decimal decimalValue)
{
return $"{decimalValue:C}";
}
}
相關問題
- 1. 根據貨幣代碼將貨幣格式設置爲貨幣
- 2. 未格式化貨幣格式貨幣
- 3. 如何將貨幣格式化爲近似美元的貨幣?
- 4. 格式貨幣
- 5. 貨幣格式
- 6. 貨幣格式
- 7. 印度貨幣的PHP貨幣格式?
- 8. 數/貨幣格式
- 9. C#格式十進制貨幣/貨幣
- 10. 如何設置貨幣格式
- 11. 設置列格式爲貨幣
- 12. 將貨幣格式化爲asp.net mvc c中的貨幣#
- 13. Sencha貨幣格式
- 14. 貨幣格式C++
- 15. C#貨幣格式
- 16. C#格式貨幣
- 17. Javascript貨幣格式
- 18. 格式化貨幣
- 19. 格式化貨幣
- 20. ZF2貨幣格式
- 21. 貨幣laravel格式
- 22. 貨幣格式laravel
- 23. 格式化貨幣
- 24. INR貨幣格式
- 25. PHP貨幣格式
- 26. 將貨幣格式化爲字符串時指定貨幣
- 27. 如何將數字格式設置爲貨幣?
- 28. 貨幣格式爲「£##,## 0.00」
- 29. 爲貨幣格式UITextField
- 30. 轉換爲貨幣格式
如果量可爲空的小數會發生什麼? – Groppe 2016-04-27 19:17:03
我編輯了原文給你一個例子。 – Robaticus 2016-04-30 01:58:02
您還可以在字母C之後指定所需的小數位數,例如,如果您的值爲12.123並且您只希望輸出中有2位小數位,則可以使用String.Format(「{0:C2}」, _amount.Value。此外,如果您希望將字符串格式化爲特定文化,則可以指定IFormatProvider。 – 2017-10-24 18:49:34