Serializing double value to JSON string

2019-09-17 19:26发布

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>.

2条回答
Deceive 欺骗
2楼-- · 2019-09-17 20:01

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.

查看更多
Emotional °昔
3楼-- · 2019-09-17 20:10

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.

查看更多
登录 后发表回答