Search code examples
javascriptparseintparsefloat

How do I avoid needing to use parseFloat/Int, number() in the first place with JavaScript?


When adding some non-quoted object values, it sometimes concatenates the values instead of actually adding them, so I use the parseInt or parseFloat function around both of the 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 find it really annoying that I need to use parseFloat. Any way to get around this?


Solution

  • 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);