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);
} }
So you have a string like: 50%
? How about:
var percent = "50%";
var result = parseFloat(percent) / 100.0;
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];
Assuming the "%" is on the right hand of the string, just use parseFloat(s)/100
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%"]))
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.