Skip to content

Parsing Float from Json without decimal point #199

@LeeCampbell

Description

@LeeCampbell

JSON numeric data may be formatted in either standard numeric format or using exponential notation. e.g. 0.0123 or 1.23E-02.

The message pack library currently will drop the value if JSON data is provided in exponential format without a decimal place.

{
  "InterestRate" : 1E-6
}

Where as an equally valid value will work

{
  "InterestRate" : 1.0E-6
}

This can be reproduced with a simple sample

var jsonLiteral = @"{""InterestRate"":1.0E-6}";
var bytes = MessagePack.MessagePackSerializer.FromJson(jsonLiteral);
var roundTripJson = MessagePack.MessagePackSerializer.ToJson(bytes);
Console.WriteLine(roundTripJson);	
//prints {"InterestRate":1E-06}

It is interesting to note that when round tripped, the decimal place has been removed. i.e. 1.0E-6 --> 1E-06. So it produces a JSON literal value, that itself can not consume.

This can be proved by simply extending the sample to consume the round tripped JSON literal value.
In this sample we see an IndexOutOfRangeException thrown as the value of 0.000006 is never written to the messagepack output.

var jsonLiteral = @"{""InterestRate"":1.0E-6}";
var bytes = MessagePack.MessagePackSerializer.FromJson(jsonLiteral);
jsonLiteral = MessagePack.MessagePackSerializer.ToJson(bytes);
Console.WriteLine(jsonLiteral); //prints {"InterestRate":1E-06}
bytes = MessagePack.MessagePackSerializer.FromJson(jsonLiteral);
jsonLiteral = MessagePack.MessagePackSerializer.ToJson(bytes);  //IndexOutOfRangeException "Index was outside the bounds of the array."


This can be corrected on https://github.com/neuecc/MessagePack-CSharp/blob/master/src/MessagePack/Internal/TinyJsonReader.cs#L243 where then check in only for the '.' character, but if 'e' and 'E' were included, then the subsequent code will parse the number correctly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions