我们如何在c#中更新两位小数精度?

问题描述 投票:0回答:1

我有一个模型对象,其小数位数是多少?金额栏。数据库中的值为 35.00,但从 API 传递时值为 35.0。我正在尝试将小数精度更新两位数。大约 35 点。请问有人帮忙解决这个问题吗?

我有一个模型对象,其小数位数是多少?金额栏。数据库中的值为 35.00,但从 API 传递时值为 35.0。我正在尝试将小数精度更新两位数。大约 35:00。

型号.金额; -- 35.0 dbEmployee.Amount; -- 35:00 这里我想将 update objAmount 更新为 35.00。

c# asp.net-core
1个回答
0
投票
This seems like you are updating decimal precision value . you can try this:
First create a helper method like below,

using Newtonsoft.Json;
/// <summary>
/// Classs.
/// </summary>
public class NullableDecimalFormatConverter : JsonConverter<decimal?>
{
    private readonly int _decimalPlaces;

    /// <summary>
    /// Initializes a new instance of the <see cref="NullableDecimalFormatConverter"/> class.
    /// </summary>
    /// <param name="decimalPlaces">Number.</param>
    public NullableDecimalFormatConverter(int decimalPlaces)
    {
        _decimalPlaces = decimalPlaces;
    }

    /// <inheritdoc/>
    public override void WriteJson(JsonWriter writer, decimal? value, JsonSerializer serializer)
    {
        if (value.HasValue)
        {
            writer.WriteValue(value.Value.ToString($"F{_decimalPlaces}"));
        }
        else
        {
            writer.WriteNull();
        }
    }

    /// <inheritdoc/>
    public override decimal? ReadJson(JsonReader reader, Type objectType, decimal? existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return null;
        }

        return Convert.ToDecimal(reader.Value);
    }
} 

ad then call this helper method as below. you ca pass your Employee class to this method.

private string SerializeObject(object? obj)
    {
        if (obj is null)
        {
            return string.Empty;
        }

        var settings = new JsonSerializerSettings();
        settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        settings.Converters.Add(new NullableDecimalFormatConverter(2));

        return JsonConvert.SerializeObject(
                                            obj,
                           `enter code here`                 Formatting.Indented,
                                            settings);
    }
© www.soinside.com 2019 - 2024. All rights reserved.