[英]javascript convert $ string to number
我有一组具有$ 1.00,$ 1654.31等值的表单字段,我只想将它们转换为数字字符串,以便我可以计算这些值。
即时通讯遍历每个,但登录到控制台时一直保持NaN。
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val() ) );
});
每次返回NaN时,我想知道是否有一种简单的方法可以将美元值字符串转换为仅用于计算的数值?
提前致谢
尝试
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val().replace('$','') ) );
});
var numberWithoutDollar = numberWithDollar.replace(/^\$/, '');
您必须删除数字以外的所有内容.
, -
和+
。
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val().replace(/[^\d\.\+-]/g, "") ) );
});
例子:
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.