'Convert percent into a decimal in html/ javascript

Javascript:

   var validate(s) = s.match ^( 100(?:\.0{1,2})? | 0*?\.\d{1,2} | \d{1,2}(?:\.\d     {1,2})? )% $ != null; 

   var str = value.match(/\/\/%//g);

    if(converted==NaN){
            alert('Input was not a number');
    }
    else if(converted != null) {

            var fracToDecimal = eval (value);

            alert(fracToDecimal);
    }
    else if(converted = str) {

            var percToDecimal = value/100;

            alert(percToDecimal);
    } }


Solution 1:[1]

So you have a string like: 50%? How about:

var percent = "50%";
var result = parseFloat(percent) / 100.0;

Solution 2:[2]

If you use parseFloat, it will read the string up until the first non-number character (the %)

var x = '20.1%';
var y = parseFloat(x); // 20.1

Then you can check if it's NaN, and convert it.

if(!isNaN(y)){
    y /= 100; // .201
)

Note: You need to use isNaN because NaN === NaN is false (JavaScript is weird).

UPDATE: I see you also have fracToDecimal in there. You don't need eval for that. Just do a simple split.

var frac = '1/2';
var nums = frac.split('/');
var dec = nums[0]/nums[1];

Solution 3:[3]

Assuming the "%" is on the right hand of the string, just use parseFloat(s)/100

http://jsfiddle.net/TrCYX/1/

Solution 4:[4]

function convertToDecimal(percent) {
let newarr =[]
for(i=0; i<percent.length; i++) {
const parsed = parseFloat(percent[i]);
  if (!Number.isNaN(parsed[i])) {
    let newval = parseFloat(percent[i]) / 100;
    //return newval;
    newarr.push(newval)
  } else {
    return 0;
  }
} return newarr;
}
console.log(convertToDecimal(["33%", "98.1%", "56.44%", "100%"]))

Solution 5:[5]

I'm very late, but keeping it as itself if it is a decimal goes like this

let val = "100%"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1
val = 1 //or val = "1"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rfunduk
Solution 2
Solution 3 sparebytes
Solution 4 S Gabale
Solution 5 helper22