Skip to content

Commit

Permalink
Handle numbers ending in .0, .00 and so on
Browse files Browse the repository at this point in the history
* Add tests for parsing numbers ending in .0

Tests fails when parseTrueNumberOnly:true

* Handle numbers that ends with .0

Fixes failing test from previous commit
  • Loading branch information
HCanber committed Apr 2, 2020
1 parent 74b5586 commit ea5d544
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
57 changes: 57 additions & 0 deletions spec/xmlParser_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,63 @@ describe("XMLParser", function() {
expect(result).toEqual(expected);
});


it("should parse number ending in .0 for parseTrueNumberOnly:false", function () {
const xmlData = `<rootNode>
<floatTag0>0.0</floatTag0>
<floatTag1>1.0</floatTag1>
<floatTag2>2.0000</floatTag2>
<floatTag3 float="3.00"/>
</rootNode>`;
const expected = {
"rootNode": {
"floatTag0": 0,
"floatTag1": 1,
"floatTag2": 2,
"floatTag3": {
"@_float": 3
}
}
};

const result = parser.parse(xmlData, {
ignoreAttributes: false,
parseAttributeValue: true,
parseTrueNumberOnly: false
});
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
});

it("should parse number ending in .0 for parseTrueNumberOnly:true", function () {
const xmlData = `<rootNode>
<floatTag0>0.0</floatTag0>
<floatTag1>1.0</floatTag1>
<floatTag2>2.0000</floatTag2>
<floatTag3 float="3.00"/>
</rootNode>`;
const expected = {
"rootNode": {
"floatTag0": 0,
"floatTag1": 1,
"floatTag2": 2,
"floatTag3": {
"@_float": 3
}
}
};

const result = parser.parse(xmlData, {
ignoreAttributes: false,
parseAttributeValue: true,
parseTrueNumberOnly: true
});
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
});



it("should not parse values to primitive type", function() {
const xmlData = `<rootNode><tag>value</tag><boolean>true</boolean><intTag>045</intTag><floatTag>65.34</floatTag></rootNode>`;
const expected = {
Expand Down
2 changes: 1 addition & 1 deletion src/xmlstr2xmlnode.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ function parseValue(val, shouldParse, parseTrueNumberOnly) {
parsed = Number.parseInt(val, 16);
} else if (val.indexOf('.') !== -1) {
parsed = Number.parseFloat(val);
val = val.replace(/0+$/,"");
val = val.replace(/\.?0+$/, "");
} else {
parsed = Number.parseInt(val, 10);
}
Expand Down

0 comments on commit ea5d544

Please sign in to comment.