Merge pull request #377 from totalgee/negative_exponent_json

Fix JSON parsing for floats with negative exponents
This commit is contained in:
Jason Turner 2017-11-20 21:54:38 -07:00 committed by GitHub
commit 7f822be5db
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 3 deletions

View File

@ -568,6 +568,7 @@ struct JSONParser {
char c = '\0'; char c = '\0';
bool isDouble = false; bool isDouble = false;
bool isNegative = false; bool isNegative = false;
bool isExpNegative = false;
long exp = 0; long exp = 0;
if( offset < str.size() && str.at(offset) == '-' ) { if( offset < str.size() && str.at(offset) == '-' ) {
isNegative = true; isNegative = true;
@ -587,7 +588,7 @@ struct JSONParser {
if( offset < str.size() && (c == 'E' || c == 'e' )) { if( offset < str.size() && (c == 'E' || c == 'e' )) {
c = str.at(offset++); c = str.at(offset++);
if( c == '-' ) { if( c == '-' ) {
exp_str += '-'; isExpNegative = true;
} else if( c == '+' ) { } else if( c == '+' ) {
// do nothing // do nothing
} else { } else {
@ -605,7 +606,7 @@ struct JSONParser {
break; break;
} }
} }
exp = chaiscript::parse_num<long>( exp_str ); exp = chaiscript::parse_num<long>( exp_str ) * (isExpNegative?-1:1);
} }
else if( offset < str.size() && (!isspace( c ) && c != ',' && c != ']' && c != '}' )) { else if( offset < str.size() && (!isspace( c ) && c != ',' && c != ']' && c != '}' )) {
throw std::runtime_error(std::string("JSON ERROR: Number: unexpected character '") + c + "'"); throw std::runtime_error(std::string("JSON ERROR: Number: unexpected character '") + c + "'");

5
unittests/json_14.chai Normal file
View File

@ -0,0 +1,5 @@
assert_equal(from_json("9.9e-02"), 9.9e-02)
assert_equal(from_json("-13.57e+3"), -13570.0)
assert_equal(from_json("1E-01"), 0.1)
assert_equal(from_json("-314159e-5"), -3.14159)
assert_equal(from_json("5e+04"), 50000)