的WebAPI,JSON.Net和丢失小数precision [英] WebAPI, JSON.Net and losing decimal precision

查看:935
本文介绍了的WebAPI,JSON.Net和丢失小数precision的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一点使用的WebAPI和JSON.Net一个奇怪的问题。当去连载已提交给我的API JSON我似乎失去precision!我提交十进制到小数点后3位,但是当值物化在我的对象只对2位小数!

I've come across a bit of a strange issue using WebAPI and JSON.Net. When de-serialising JSON that has been submitted to my API I seem to be losing precision! I'm submitting the decimal to 3 decimal places, but when the values materialises in my object it's only to 2 decimal places!

的JSON我提出这个样子的:

The JSON I submit looks like this:

{
    id: 1,
    name: 'mock data',
    value: 123.456
}

这是绑定到一个类看起来是这样的:

This is bound to a class that looks something like this:

public class MockObject {
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Value { get; set; }
}

只是为了完整性这基本上是我的WebAPI的方法是什么样子:

Just for completeness this is basically what my WebAPI method looks like:

public HttpResponseMessage Post (MockObject data) {
    // do something with the value here and return the relevant response
}

我通过一个jQuery Ajax请求提交的数据,但我可以看到张贴的值是完全按照我期望在提交之前和提琴手检查在Chrome浏览器开发工具的值时,一旦他们已经走了过线

I'm submitting the data via a JQuery ajax request, but I can see the posted values are exactly as I expect when inspecting the values in the chrome dev tools before submitting and in fiddler once they've gone "over the wire".

当它得到做一些与在发表方法物化对象的值的数值是123.45。

When it gets to doing something with the materialised object in the Post method the value of "Value" is 123.45.

如果我提交2个或更少的小数位数(即123.4或123.45)的价值被反序列化不如预期,但是如果我提交超过2位数(即123.456或123.4567等值始终得到反序列化到123.45。

If I submit 2 or fewer decimal places (i.e. 123.4 or 123.45) the value gets de-serialised as expected, however if I submit more than 2 decimal places (i.e. 123.456 or 123.4567 etc the value is always getting de-serialised to 123.45.

任何人都遇到过这个问题?有什么建议?

Anyone else come across this issue? Any suggestions?

推荐答案

我设法排序了这一点。

I managed to sort this out.

在结束时的问题正在被其中包含货币数字格式的事实,即培养物被设置而引起的。货币数字格式指明应当被用于十进制值的小数位的数量。

In the end the problem was being caused by the fact that the culture was being set which contains currency number formatting. The currency number format specifies the number of decimal places which should be used for decimal values.

要解决这个问题,现在我在 Global.ascx.cs CultureInfo.InvariantCulture 的新实例C $ C>像这样:

To fix this I now set the WebApi JSON serializer culture to a new instance of CultureInfo.InvariantCulture in Global.ascx.cs like so:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Culture = new CultureInfo(string.Empty) {
    NumberFormat = new NumberFormatInfo {
        CurrencyDecimalDigits = 5
    }
};

这意味着,十进制值能有什么最多5位小数。

This means that decimal values can have anything up to 5 decimal places.

这篇关于的WebAPI,JSON.Net和丢失小数precision的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆