javascript将$ string转换为数字

时间:2013-09-23 01:35:34

标签: javascript jquery

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

我循环遍历每一个,但在我登录控制台时继续获得NaN。

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

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

提前致谢

4 个答案:

答案 0 :(得分:3)

尝试

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

答案 1 :(得分:1)

var numberWithoutDollar = numberWithDollar.replace(/^\$/, '');

答案 2 :(得分: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

答案 3 :(得分:0)

跳过美元符号。

parseFloat($(this).val().substr(1))
相关问题