You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JQuery中从ASP.Net Web API返回的JSON获取正确浮点值

解决ASP.NET Web API v2返回JSON时Price属性有效数字丢失的问题

我来帮你一步步排查并解决这个问题,咱们从模型定义、API序列化配置到前端展示全流程梳理:

1. 先确认ProductModel的Price属性类型

首先得确保你的ProductModel里Price用的是decimal类型(金额场景首选decimal,避免精度丢失),别用int或者float,不然本身就会砍掉小数部分:

public class ProductModel
{
    public int Id { get; set; }
    public string Description { get; set; }
    // 必须用decimal来保留金额的完整精度
    public decimal Price { get; set; }
}

2. 配置Web API的JSON序列化规则

从你给出的XML格式响应来看,你的API可能默认用了DataContractSerializer,这种序列化器对decimal的处理会自动去掉末尾的零。咱们要切换成Json.NET(Newtonsoft.Json)并配置它保留完整的有效数字:

步骤1:修改WebApiConfig配置

打开App_Start/WebApiConfig.cs,添加Json序列化的自定义配置:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // 移除XML格式化器,让API默认返回JSON
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        
        // 获取Json序列化设置
        var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
        // 可选:把属性名转成驼峰命名(适配前端习惯)
        jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        // 关键:添加自定义Decimal转换器,强制保留所有精度
        jsonSettings.Converters.Add(new DecimalPrecisionConverter());
    }
}

// 自定义Decimal转换器,保证序列化时不丢失有效数字
public class DecimalPrecisionConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(decimal) || objectType == typeof(decimal?);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null) return null;
        return decimal.Parse(reader.Value.ToString());
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value == null)
        {
            writer.WriteNull();
            return;
        }
        // 直接写入原始decimal值,不做自动截断
        writer.WriteValue((decimal)value);
    }
}

3. 用jQuery获取并展示格式化后的产品数据

现在API返回的JSON里Price应该有完整的有效数字了,接下来写前端代码请求并渲染:

<div id="productContainer"></div>

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(function() {
    // 调用你的Web API接口
    $.get("/api/products")
    .done(function(products) {
        let productHtml = "<ul class='product-list'>";
        $.each(products, function(index, product) {
            // 用toFixed()统一展示两位小数(根据你的业务需求调整位数)
            let formattedPrice = product.price.toFixed(2);
            productHtml += `
                <li>
                    <h3>${product.description}</h3>
                    <p class="price">价格:$${formattedPrice}</p>
                </li>
            `;
        });
        productHtml += "</ul>";
        $("#productContainer").html(productHtml);
    })
    .fail(function(xhr) {
        $("#productContainer").text("加载产品列表失败,请稍后重试");
        console.error("请求错误:", xhr.responseText);
    });
});
</script>

额外排查点

如果还是有问题,可以检查这两处:

  • 数据库里的Price字段类型:比如SQL Server要设为decimal(18,2)这类带固定小数位的类型
  • 浏览器开发者工具:在Network标签里查看API返回的原始JSON,确认Price数值是否正确

内容的提问来源于stack exchange,提问作者Swayam Deep Dash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:01:51