How do I avoid using parseFloat / Int, number () in the first place with JavaScript?
When adding some unquoted values ββto the object, it sometimes concatenates the values ββinstead of actually adding them, so I use the parseInt or parseFloat function for both values.
Example:
var testobj =
{
'test1':
{
'rect': {x:100, y:0, w:0, h:0}
},
'line2':
{
'rect': {x:0, y:0, w:200, h:0}
}
}
var result = parseFloat(testobj['test1'].rect.x) + parseFloat(testObj['test2'].rect.w);
console.log(result); // will give me 300
result = testobj['test1'].rect.x + testObj['test2'].rect.w;
console.log(result); // will give me 100300
I am very frustrated that I need to use parseFloat. Any way to get around this?
source to share
You can force the variable to become a number if you use +
in front of the variable, check the example below.
var testobj = {
'test1':
{
'rect': {x:'100', y:'0', w:'0', h:'0'}
},
'line2':
{
'rect': {x:'0', y:'0', w:'200', h:'0'}
}
}
var result = +(testobj['test1'].rect.x) + +(testobj['line2'].rect.w);
console.log(result); // will give me 300
result = testobj['test1'].rect.x + testobj['line2'].rect.w;
console.log(result); // will give me 100300
var a = '11';
var b = '22';
var c = '1.25';
var d = '2.25';
console.log('"11" + "22" = ' + a + b);
console.log('+"11" + +"22" = ' + (+a + +b));
console.log(+"11" + +"22");
console.log(c + d);
console.log(+c + +d);
source to share
You can write a small function that converts all gated int / float keys of obj to int / float, so you don't have to take extra steps many times during computation.
function parseNumKeys(obj) {
if( typeof obj == "object" ) {
for(var key in obj){
var num = parseFloat(obj[key]);
isNaN(num)? parseNumKeys(obj[key]) : obj[key] = num;
}
}
}
Pass your object to the function above:
var testobj = {
'test1':
{
'rect': {x:'100', y:'0', w:'0', h:'0'}
},
'line2':
{
'rect': {x:'0', y:'0', w:'200', h:'0'}
}
}
console.log("before parseNumKeys called: \n", testobj);
parseNumKeys(testobj);
console.log("after parseNumKeys called: \n", testobj);
// before parseNumKeys called:
// { test1: { rect: { x: '100', y: '0', w: '0', h: '0' } },
// line2: { rect: { x: '0', y: '0', w: '200', h: '0' } } }
// after parseNumKeys called:
// { test1: { rect: { x: 100, y: 0, w: 0, h: 0 } },
// line2: { rect: { x: 0, y: 0, w: 200, h: 0 } } }
Now result = testobj['test1'].rect.x + testobj['line2'].rect.w;
will give 300 not 100300, without additional processing.
source to share