繁体   English   中英

如何在Xamarin.Android中的小数点后显示2或3个数字?

[英]How to display 2 or 3 numbers after the decimal separator in Xamarin.Android?

我有具有属性SellPrice Article模型。 我想在任何使用它的地方都用小数点分隔符后的2数字显示。 在小数点分隔符之后,它始终具有2数字的值,但是当price2,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 ...。 ..是否有任何方法可以在模型中将其指定为属性?

为什么不使用私有字段将值保存在其中并具有两个属性SellPriceSellPriceString ,如下所示,这种方式可以重新使用SellPriceString属性,而不是每次要使用SellPrice属性时都格式化字符串:

decimal _sellPrice;
public decimal SellPrice
{
    get
    {
        return _sellPrice;
    }
    set
    {
        _sellPrice = value;
    }
}

public string SellPriceString
{
    get
    {
        return _sellPrice.ToString("N2");
    }
}

在您的ToString方法中使用标准数字格式作为参数。 您可以对“ Quantity属性进行完全相同的操作,但是使用“标准数字格式”“ N3”,请再次参考链接以获取有关该格式的更多信息。

如何在Xamarin.Android中的小数点后显示2或3个数字?

您可以尝试使用SellPrice.ToString("C2") ,请参阅: 标准数字格式字符串

例如:

SellPrice = 12.545646M;
Debug.WriteLine("SellPrice.ToString(C2) == " + SellPrice.ToString("C2"));

[0:] SellPrice.ToString(C2) == ¥12.55
public decimal Quantity { get; set; }
public string QuantityDisplay
{
    get
    {
        return String.Format("{0:0.000}", Quantity);
    }
}
[Column("sell_price")]
[XmlElement(ElementName = "sell_price", Namespace = "http://tempuri.org/DataSet1.xsd")]
//[DisplayFormat(DataFormatString = "{0:0.00}")]
public decimal SellPrice { get; set; }
public string SellPriceDisplay
{
    get
    {
        return String.Format("{0:0.00}", SellPrice);
    }
}

SellPrice我想进行计算的地方,我都会使用QuantitySellPrice属性。 只要我想显示QuantitySellPrice我用QuantityDisplaySellPriceDisplay性能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM