mirror of
https://github.com/ChaiScript/ChaiScript.git
synced 2025-12-06 16:57:04 +08:00
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:
parent
244b5b224b
commit
561c5bc981
@ -567,10 +567,13 @@ struct JSONParser {
|
|||||||
std::string val, exp_str;
|
std::string val, exp_str;
|
||||||
char c = '\0';
|
char c = '\0';
|
||||||
bool isDouble = false;
|
bool isDouble = false;
|
||||||
|
bool isNegative = false;
|
||||||
long exp = 0;
|
long exp = 0;
|
||||||
for (; offset < str.size() ;) {
|
for (; offset < str.size() ;) {
|
||||||
c = str[offset++];
|
c = str[offset++];
|
||||||
if( (c == '-') || (c >= '0' && c <= '9') ) {
|
if( c == '-' ) {
|
||||||
|
isNegative = true;
|
||||||
|
} else if( c >= '0' && c <= '9' ) {
|
||||||
val += c;
|
val += c;
|
||||||
} else if( c == '.' ) {
|
} else if( c == '.' ) {
|
||||||
val += c;
|
val += c;
|
||||||
@ -608,12 +611,12 @@ struct JSONParser {
|
|||||||
--offset;
|
--offset;
|
||||||
|
|
||||||
if( isDouble ) {
|
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 {
|
} else {
|
||||||
if( !exp_str.empty() ) {
|
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 {
|
} else {
|
||||||
return JSON(chaiscript::parse_num<long>( val ));
|
return JSON((isNegative?-1:1) * chaiscript::parse_num<long>( val ));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1 +1,2 @@
|
|||||||
assert_equal(from_json("100"), 100)
|
assert_equal(from_json("100"), 100)
|
||||||
|
assert_equal(from_json("-100"), -100)
|
||||||
|
|||||||
@ -1 +1,2 @@
|
|||||||
assert_equal(from_json("1.234"), 1.234)
|
assert_equal(from_json("1.234"), 1.234)
|
||||||
|
assert_equal(from_json("-1.234"), -1.234)
|
||||||
|
|||||||
@ -1,2 +1,2 @@
|
|||||||
assert_equal(from_json("[1,2,3]"), [1,2,3])
|
assert_equal(from_json("[1,-2,3]"), [1,-2,3])
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user