我有 Article
模型,它有属性 SellPrice
。我希望无论我在哪里使用它,都在小数点分隔符后显示 2
数字。它总是在小数分隔符后具有 2
数字的值,但是当 price
例如 2,30
时,它显示为 2, 3
,我想显示为 2,30
。同样的事情发生在同一 Article
模型中的属性 Quantity
我希望它在小数点分隔符后显示 3 个数字,例如,如果它的值为 1, 1
显示为 1,100
。对于 SellPrice
,我尝试了以下方法:
[Column("sell_price")]
[XmlElement(ElementName = "sell_price", Namespace = "http://tempuri.org/DataSet1.xsd")]
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal SellPrice { get; set; }
但是 DisplayFormat
带有红色下划线,我不允许使用 System.ComponentModel.DataAnnotations
导入它的命名空间。我想它已被弃用。为了在小数点分隔符后显示 3
数字,我什至没有发现任何过时的东西。我找到了很多使用 String.Format
的方法,但我在项目的很多地方都使用了 SellPrice
和 Quantity
并且我不想每次使用模型属性编写 String.Format
......有没有办法在模型中指定它作为属性?
最佳答案
为什么不使用私有(private)字段来保存值并有两个属性 SellPrice
和 SellPriceString
如下,这样你就可以重新使用 SellPriceString
属性,而不是每次要使用 SellPrice
属性时都格式化字符串:
decimal _sellPrice;
public decimal SellPrice
{
get
{
return _sellPrice;
}
set
{
_sellPrice = value;
}
}
public string SellPriceString
{
get
{
return _sellPrice.ToString("N2");
}
}
使用 Standard Numeric Format作为 ToString
方法中的参数。您可以对 Quantity
属性执行完全相同的操作,但使用标准数字格式“N3”,再次引用链接以获取有关该格式的更多信息。
关于c# - 如何在 Xamarin.Android 中的小数点分隔符后显示 2 个或 3 个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48659902/