[英]javascript convert $ string to number
I have a set of form fields that have values like $1.00, $1654.31 and i would like to convert them to a numerical string only so i can calculate the values. 我有一组具有$ 1.00,$ 1654.31等值的表单字段,我只想将它们转换为数字字符串,以便我可以计算这些值。
Im looping over each one, but keep getting NaN when i log to the console. 即时通讯遍历每个,但登录到控制台时一直保持NaN。
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val() ) );
});
each time it returns NaN, im wondering whether there is an easy way to make a dollar value string convert to a numerical value only for calculating ? 每次返回NaN时,我想知道是否有一种简单的方法可以将美元值字符串转换为仅用于计算的数值?
thanks in advance 提前致谢
Try 尝试
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val().replace('$','') ) );
});
var numberWithoutDollar = numberWithDollar.replace(/^\$/, '');
You have to remove everything but numbers, .
您必须删除数字以外的所有内容
.
, -
and +
. ,
-
和+
。
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val().replace(/[^\d\.\+-]/g, "") ) );
});
Examples: 例子:
parseFloat("-1.00".replace(/[^\d\.\+-]/g, ""))
// -1
parseFloat("+1654.31 ".replace(/[^\d\.\+-]/g, ""))
// 1654.31
刚刚跳过美元符号。
parseFloat($(this).val().substr(1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.