将百分比转换为 html/javascript 中的小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11088562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert percent into a decimal in html/ javascript
提问by user1464427
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);
} }
回答by rfunduk
So you have a string like: 50%
? How about:
所以,你有喜欢的字符串:50%
?怎么样:
var percent = "50%";
var result = parseFloat(percent) / 100.0;
回答by Rocket Hazmat
If you use parseFloat
, it will read the string up until the first non-number character (the %
)
如果您使用parseFloat
,它将读取字符串直到第一个非数字字符(%
)
var x = '20.1%';
var y = parseFloat(x); // 20.1
Then you can check if it's NaN
, and convert it.
然后你可以检查它是否是NaN
,并转换它。
if(!isNaN(y)){
y /= 100; // .201
)
Note: You need to use isNaN
because NaN === NaN
is false
(JavaScript is weird).
注意:您需要使用isNaN
因为NaN === NaN
是false
(JavaScript 很奇怪)。
UPDATE: I see you also have fracToDecimal
in there. You don't need eval
for that. Just do a simple split
.
更新:我看到你也在fracToDecimal
那里。你不需要eval
那个。做一个简单的split
.
var frac = '1/2';
var nums = frac.split('/');
var dec = nums[0]/nums[1];
回答by sparebytes
Assuming the "%" is on the right hand of the string, just use parseFloat(s)/100
假设“%”在字符串的右侧,只需使用 parseFloat(s)/100