【问题标题】:How to display decimal data type with two decimal place in .Net Core rest API response如何在.Net Core rest API响应中显示带两位小数的十进制数据类型
【发布时间】:2021-07-05 13:54:19
【问题描述】:

我正在开发 .net core 3.1 (C#) 中的 REST API 项目。我的模型如下。

 public class Transaction {
        [SwaggerSchema("Item code.")]
        [Required]
        [MaxLength(20)]
        public string ItemCode { get; set; }

        /// <example>1</example>
        [SwaggerSchema("Transaction type.")]
        public int TransactionType { get; set; }
        
        /// <example>50</example>
        [SwaggerSchema("Transaction amount.")]
        [Required]       
        [Range(0,int.MaxValue,ErrorMessage ="Amount must be greater than zero.")]  
        public decimal Amount { get; set; }

        /// <example>ABC45345</example>
        [SwaggerSchema("Comment related to the transaction.")]
        [MaxLength(50)]
        public string Comment { get; set; }
} 

我使用这个模型 Transaction 对象作为我的 Post 方法的参数。问题是,当用户提供金额为 .9 时,它会失败并出现错误。

此外,存储在 2.00、150.00 等数据库中的值在 GET 调用中显示不带小数位。我的客户希望查看所有小数点后两位的金额。有人可以建议我们是否可以通过其他方式处理此十进制数据类型以接受 .77(不带前导零)并显示两个小数点,无论该值是否有小数位?

我们可以使用字符串数据类型来管理它,但我不想从十进制更改数据类型。请指教。

【问题讨论】:

  • 您是否尝试添加注释[DisplayFormat(DataFormatString = "0.0")]
  • 是的,@Steve。我已经试过了,输出没有效果。
  • Api 提供 json 响应。使用 json 的人应该在 UI 端以他们想要的任何格式显示它。格式化不是 api 的工作。

标签: c# json .net .net-core rest


【解决方案1】:

在不更改数据类型的情况下,我没有看到任何处理此问题的方法。我改变了我的代码如下

private string _amount;
[SwaggerSchema("Transaction amount.")]
    [Required]
    public string Amount
    {
        get => _amount;
        set => _amount = decimal.Parse(value, NumberStyles.AllowDecimalPoint,
            new CultureInfo("en-US")).ToString("F2");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 2012-12-07
    • 1970-01-01
    • 2020-03-05
    • 2010-10-22
    • 2010-09-14
    • 2019-05-25
    • 2019-06-30
    相关资源
    最近更新 更多