简体   繁体   English

下面的小数怎么换算? 到字符串(“F2”)

[英]How to convert the following decimal? to String(“F2”)

I have Decimal?我有十进制? Amount数量

In my model I have a value as @item.Sales, which I`m trying to write as @item.Sales.ToString("F2").在我的模型中,我有一个值为@item.Sales,我试图将其写为@item.Sales.ToString("F2")。

I`m having the message error Error 1 No overload for method 'ToString' takes 1 arguments我有消息错误错误 1 ​​方法“ToString”没有重载需要 1 个参数

How can I achieve the above我怎样才能实现上述目标

If it's a nullable decimal, you need to get the non-nullable value first:如果是可以为空的小数,则需要先获取不可为空的值:

@item.Sales.Value.ToString("F2")

Of course, that will throw an exception if @item.Sales is actually a null value, so you'd need to check for that first.当然,如果@item.Sales实际上是一个空值,那会抛出一个异常,所以你需要先检查一下。

You could create an Extension method so the main code is simpler您可以创建一个扩展方法,以便主代码更简单

  public static class DecimalExtensions
  {
    public static string ToString(this decimal? data, string formatString, string nullResult = "0.00")
    {
      return data.HasValue ? data.Value.ToString(formatString) : nullResult;
    }
  }

And you can call it like this:你可以这样称呼它:

  decimal? value = 2.1234m;
  Console.WriteLine(value.ToString("F2"));
if( item.Sales.HasValue )
{
    item.Sales.Value.ToString(....)
}
else
{
 //exception handling
}

Use the unary ?使用一元 ? operator to run .ToString() only when there's an object仅当有对象时才运行 .ToString() 的运算符

@item.Sales?.ToString("F2")

Or use the double ??还是用双?? operator thus makes it non-nullable:运算符因此使其不可为空:

@((item.Sales??0).ToString("F2"))

This is better than @item.Sales.Value.Tostring("F2") because if you don't check for null value before using .ToString("F2") the code will break at runtime.这比@item.Sales.Value.Tostring("F2")更好,因为如果在使用.ToString("F2")之前不检查空值,代码将在运行时中断。

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

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