How to compare two percentage strings

Viewed 406

I have two strings: 50% and 60%. I'm trying to compare the two strings and figure out that 60% is bigger than 50%. What would be the easiest and most clean way to compare the two strings? I can always remove the % sign, convert the strings to ints and compare them. But is there a better way?

4 Answers

You can use parseInt to parse only the numeric part.

let x = "50%";
let y = "60%";
parseInt(x)>parseInt(y)?console.log(`${x} is greater than ${y}`):console.log(`${y} is greater than ${x}`);

Console: 60% is greater than 50%
let percentage1 = parseFloat('50%');
let percentage2 = parseFloat('60%');

if (percentage1 <= percentage2) {
    // Code here
}
function cmpPercentages(str1, str2){
    var per1 = parseFloat(str1);
    var per2 = parseFloat(str2);
    if(per1 > per2){
        return 1;
    }else if(per2 > per1){
        return -1;
    }else{
        return 0;
    }
}

Where 1 means that the first percentage is higher, -1 that the first percentage is smaller than the second and 0 that they are equal, just like localeCompare's result.

Related