If you use JObject.Parse
, in order to do what you need, your value must be a string. If it's a floating point value, you won't get its decimals. Check out this example:
string json = "{ sValue1: '9.00', sValue2: '9.0000', dValue1: 9.00, dValue2: 9.0000 }";
JToken token = JObject.Parse(json);
// prints 9.00, or 9,00 if comma is your decimal separator
Console.WriteLine((decimal)token.SelectToken("sValue1"));
// prints 9.00 regardless of your decimal separator
Console.WriteLine((string)token.SelectToken("sValue1"));
// prints 9.0000, or 9,0000 if comma is your decimal separator
Console.WriteLine((decimal)token.SelectToken("sValue2"));
// prints 9.0000 regardless of your decimal separator
Console.WriteLine((string)token.SelectToken("sValue2"));
// All these print 9
Console.WriteLine((decimal)token.SelectToken("dValue1"));
Console.WriteLine((string)token.SelectToken("dValue1"));
Console.WriteLine((decimal)token.SelectToken("dValue2"));
Console.WriteLine((string)token.SelectToken("dValue2"));
Casting as double
always removes trailing zeros.
Summarizing, these are the options:
- String => string: exact outcome
- String => decimal: exact outcome if the decimal separator matches
- String => float/double: without trailing zeros
- Float => whatever: without trailing zeros
Just for the record, decimal
data type keeps track of the precision used, so it knows if there are trailing zeros.
If you already have a class for all the properties in the JSON string, you can use JsonConvert.DeserializeObject
, which keeps the trailing zeros if you store those in a string even though if they come as float. You can see this in CodingYoshi's answer.
PS: As others mentioned, numeric values should be stored as such in the DB, but that's for another question.