c# - 如何在 Xamarin.Android 中的小数点分隔符后显示 2 个或 3 个数字?

标签 c# .net xamarin xamarin.android decimal

我有 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 的方法,但我在项目的很多地方都使用了 SellPriceQuantity 并且我不想每次使用模型属性编写 String.Format ......有没有办法在模型中指定它作为属性?

最佳答案

为什么不使用私有(private)字段来保存值并有两个属性 SellPriceSellPriceString 如下,这样你就可以重新使用 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/

相关文章:

c# - Prism.Unity.Wpf问题: UnityServiceLocatorAdapter is missing after update

c# - Blazor 中的 "The attribute names could not be inferred from bind attribute ' 绑定(bind)值 '"错误

c# - 用于简单 .NET 应用程序的 ORM

c# - 如何阻止用户更改查询字符串

c# - Xamarin.iOS 新的默认项目模板应用程序显示错误 : SecTaskLoadEntitlements failed error=22

android - 从 WP8/WPF 转向 android 开发的建议

c# - 为什么适配器不工作?

c# - PropertyGrid - 动态加载下拉值

c# - WPF 中的高性能绘图控件

android - Xamarin android 应用程序在恢复时崩溃