首页 > 解决方案 > 格式化包含公式的 get/return

问题描述

我对如何格式化下面的 get/return 以使小数点后只有 2 位数字感到有些困惑,非常感谢任何帮助。

public decimal? aExample { get; set; }
public decimal? bExample { get; set; }

public decimal? Combined
{
    get { return aExample / bExample; }
}

[Display(Name = @"ABC %")]
public decimal? Combined => aExample.NullableDivide(bExample);

标签: c#asp.net-mvcasp.net-core

解决方案


您可以使用Math.Round()功能,

//Important: This will loose precision of result. It will round value to its closed value
public decimal? Combined
{
    get { 
        return aExample == null || bExample == null ? 
            null
            : Math.Round((aExample / bExample) ?? default(decimal), 2);  //Return result with 2 precision.
    }
}

在线尝试:.NET FIDDLE


推荐阅读