Skip to content Skip to sidebar Skip to footer

Javascript Handling Fractions In Variables

I'm new to programming and was trying to write a simple program to find the slope of a line, and I was wondering how I could handle variables with fractions in them. Currently, if

Solution 1:

Dont use eval! Unless you know what eval is, why you should and shouldnt use it.

If you simply want to allow fractions then you should allow for parsing it. For instance you could simple write your code as such:

/*
* Tries to parse a users input, returns {@param input} as a number or
* attempts to parse the input as a fraction.
* @return Number or NaN if an invalid number or unparseable
*/functionparseUserInput(input) {
    var res = +input;
    if(isNaN(res)) {
        // try parsing as fractionvar strval = String(input);
        var ix = strval.indexOf('/');
        if(ix !== -1) {
            try {
                res = strval.substring(0, ix) / strval.substring(ix+1);
            } catch(e) {
            }
        }
    }
    returnisFinite(res) ? res : NaN;
}

var oneX = parseUserInput(prompt ("what is the X of the first coordinate?"));
var oneY = parseUserInput(prompt ("what is the Y of the first coordinate?"));
var twoX = parseUserInput(prompt ("what is the X of the second coordinate?"));
var twoY = parseUserInput(prompt ("what is the Y of the second coordinate?"));

Or a very pretty way of writing it using @Jonasw's suggestion.

/*
* Tries to parse a users input, returns {@param input} as a number or
* attempts to parse the input as a fraction.
* @return Number or NaN if an invalid number or unparseable
*/functionparseUserInput(input) {
  return +input.split("/").reduce((a,b)=> a/(+b||1));
}

Post a Comment for "Javascript Handling Fractions In Variables"