Handle negative numbers in JSONParse::parse_number

- fix issue #334, where negative numbers loaded from JSON were being
  parsed as 0.
- add unit tests to cover these cases.
This commit is contained in:
Glen Fraser 2017-03-14 12:01:51 +01:00
parent 244b5b224b
commit 561c5bc981
4 changed files with 10 additions and 5 deletions

View File

@ -567,10 +567,13 @@ struct JSONParser {
std::string val, exp_str;
char c = '\0';
bool isDouble = false;
bool isNegative = false;
long exp = 0;
for (; offset < str.size() ;) {
c = str[offset++];
if( (c == '-') || (c >= '0' && c <= '9') ) {
if( c == '-' ) {
isNegative = true;
} else if( c >= '0' && c <= '9' ) {
val += c;
} else if( c == '.' ) {
val += c;
@ -608,12 +611,12 @@ struct JSONParser {
--offset;
if( isDouble ) {
return JSON(chaiscript::parse_num<double>( val ) * std::pow( 10, exp ));
return JSON((isNegative?-1:1) * chaiscript::parse_num<double>( val ) * std::pow( 10, exp ));
} else {
if( !exp_str.empty() ) {
return JSON(static_cast<double>(chaiscript::parse_num<long>( val )) * std::pow( 10, exp ));
return JSON((isNegative?-1:1) * static_cast<double>(chaiscript::parse_num<long>( val )) * std::pow( 10, exp ));
} else {
return JSON(chaiscript::parse_num<long>( val ));
return JSON((isNegative?-1:1) * chaiscript::parse_num<long>( val ));
}
}
}

View File

@ -1 +1,2 @@
assert_equal(from_json("100"), 100)
assert_equal(from_json("-100"), -100)

View File

@ -1 +1,2 @@
assert_equal(from_json("1.234"), 1.234)
assert_equal(from_json("-1.234"), -1.234)

View File

@ -1,2 +1,2 @@
assert_equal(from_json("[1,2,3]"), [1,2,3])
assert_equal(from_json("[1,-2,3]"), [1,-2,3])