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