首页 > 解决方案 > 在 ASP.net 核心中显示 8 位小数的格式属性

问题描述

我想显示我的latitudeandlongitude到小数点后 8 位。但是,我现在默认只显示到小数点后 2 位。我应该如何更改我的模型?

模型:

    public class LocationModel
    {
        [Display(Name = "Latitude")]
        public decimal Latitude { get; set; }

        [Display(Name = "Longitude")]
        public decimal Longitude { get; set; }
    }

标签: c#asp.netasp.net-coremodeldecimal

解决方案


两种选择:

  1. 数据格式字符串
public class LocationModel
{
    [Display(Name = "Latitude")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:G8}")]
    public decimal Latitude { get; set; }

    [Display(Name = "Longitude")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:G8}")]
    public decimal Longitude { get; set; }
}
  1. 数学
public class LocationModel
{
    private decimal _latitude;
    private decimal _longitude;

    [Display(Name = "Latitude")]
    public decimal Latitude
    {
        get
        {
            return Math.Round(_latitude, 8);
        }
        set
        {
            this._latitude = value;
        }
    }

    [Display(Name = "Longitude")]
    public decimal Longitude
    {
        get
        {
            return Math.Round(_longitude, 8);
        }
        set
        {
            this._longitude = value;
        }
    }
}

推荐阅读