-1

我有一组表单字段,其值如 $1.00、$1654.31,我只想将它们转换为数字字符串,以便我可以计算这些值。

我遍历每一个,但是当我登录到控制台时不断得到 NaN。

$("input.costs").each(function( index) {
    console.log( $(this).val()  + parseFloat( $(this).val() )    );
});

每次它返回 NaN 时,我想知道是否有一种简单的方法可以将美元值字符串转换为仅用于计算的数值?

提前致谢

4

4 回答 4

3

尝试

$("input.costs").each(function( index) {
    console.log( $(this).val()  + parseFloat( $(this).val().replace('$','') )    );
});
于 2013-09-23T01:38:07.027 回答
1
var numberWithoutDollar = numberWithDollar.replace(/^\$/, '');
于 2013-09-23T01:38:06.867 回答
1

您必须删除除数字、.-之外的所有内容+

$("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
于 2013-09-23T01:38:20.383 回答
0

跳过美元符号。

parseFloat($(this).val().substr(1))
于 2013-09-23T01:39:03.577 回答