Search code examples
javascriptfunctiondecimalfractions

Javascript problems with a function not working (it converts fractions into decimals)


Let's say I have a string (like a fraction);

var num = "1/2";

Why does this work:

var y = num.split(' ');
if (y.length > 1) {
    var z = y[1].split('/');
    var a = (+y[0] + (z[0] / z[1]));
    num = a;
} else {
    z = y[0].split('/');
    if (z.length > 1) {
        a = (z[0] / z[1]);
        num = a;
    }
}

alert(num); //The alert box shows my variable now as a decimal.

And this doesn't:

function parseFractions(x) {
    var y = x.split(' ');
    if (y.length > 1) {
        var z = y[1].split('/');
        var a = (+y[0] + (z[0] / z[1]));
        x = a;
    } else {
        z = y[0].split('/');
        if (z.length > 1) {
            a = (z[0] / z[1]);
            x = a;
        }
    }
}

parseFractions(num); //Here I call my function.

alert(num);
//The alert box does not even show up. The fraction isn't converted into a decimal.

It's basically the same thing, the only difference is that in the 2nd one I tried to make that into a function so I don't have to repeat those lines of code every time I try to convert fractions into decimals.

So what am I doing wrong? Is what I am trying to accomplish possible with a function? Any light into this issue is appreciated!


Solution

  • the value of num is not updated, it is not passed by reference.

    function parseFractions(x) {
        var y = x.split(' ');
        if (y.length > 1) {
            var z = y[1].split('/');
            var a = (+y[0] + (z[0] / z[1]));
            x = a;
        } else {
            z = y[0].split('/');
            if (z.length > 1) {
                a = (z[0] / z[1]);
                x = a;
            }
        }
        return x;
    }
    
    num = parseFractions(num);  //set num with the value return from the method
    alert(num);