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
Solution 1:
So you have a string like: 50%
? How about:
var percent = "50%";
var result = parseFloat(percent) / 100.0;
Solution 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:
Assuming the "%" is on the right hand of the string, just use parseFloat(s)/100
Post a Comment for "Convert Percent Into A Decimal In Html/ Javascript"