这些是我拥有的字符串:
"test123.00"
"yes50.00"
我想将123.00和50.00相加。
我该怎么做?
我使用了parseInt()命令,但在警告框中显示NaN错误。
这是代码:
str1 = "test123.00";
str2 = "yes50.00";
total = parseInt(str1)+parseInt(str2);
alert(total);
这些是我拥有的字符串:
"test123.00"
"yes50.00"
我想将123.00和50.00相加。
我该怎么做?
我使用了parseInt()命令,但在警告框中显示NaN错误。
这是代码:
str1 = "test123.00";
str2 = "yes50.00";
total = parseInt(str1)+parseInt(str2);
alert(total);
只需这样做,你需要从你的字符串中删除除了 "数字" 和 "." 以外的字符,这样就可以起作用了。
yourString = yourString.replace ( /[^\d.]/g, '' );
你的最终代码将会是:
str1 = "test123.00".replace ( /[^\d.]/g, '' );
str2 = "yes50.00".replace ( /[^\d.]/g, '' );
total = parseInt(str1, 10) + parseInt(str2, 10);
alert(total);
为了让parseInt正常工作,您的字符串应该只包含数字数据。就像这样:
str1 = "123.00";
str2 = "50.00";
total = parseInt(str1)+parseInt(str2);
alert(total);
str1 = "test123.00";
str2 = "yes50.00";
intStr1 = str1.replace(/[A-Za-z$-]/g, "");
intStr2 = str2.replace(/[A-Za-z$-]/g, "");
total = parseInt(intStr1)+parseInt(intStr2);
alert(total);
使用 Jsfiddle 进行开发
这在逻辑上是否可能?我猜你必须采取的方法是这样的:
Str1 ="test123.00"
Str2 ="yes50.00"
如果你在test
和123.00
之间没有分隔符,那么这将是不可能解决的。
eg: Str1 = "test-123.00"
然后你可以这样分割
Str2 = Str1.split("-");
这将返回一个用“-”分割的单词数组
然后您可以执行parseFloat(Str2[1])
来获取浮点值,即123.00