Serializing double value to JSON string

空扰寡人 提交于 2019-12-13 04:41:41

问题


I'm trying to serialize a double value 1.0 into JSON value 1.0. However, the following code outputs 1 instead of 1.0:

var jsSerializer = new JavaScriptSerializer();
var json = jsSerializer.Serialize(1.0);
Console.WriteLine(json); // actual: 1, expected: 1.0

Does anyone has any idea how to accomplish this?

I though of creating a custom converter for double types by extending JavaScriptConverter, but the problem is the Serialize method is supposed to return IDictionary<string, object>.


回答1:


It doesn't matter. All numbers in Javascript are floating point numbers (IEEE 754 double precision, to be exact): whether you say

  • var x = 1 ;
  • var x = 1.0 ;
  • { x : 1 }

the net result is the same: x is a floating point number with a value of 1.




回答2:


If you need a specific text format for the value, you should serialize it as a string. JSON isn't about text representation, it's about accurately serializing and deserializing values. It only has one "Number" data type; if integer values lack a ".0" at the end, that's either because the specification says to do it that way or the specification leaves it to the implementation to decide. The value of saving 2 characters per integer is probably significant in many applications.



来源:https://stackoverflow.com/questions/21418260/serializing-double-value-to-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!