使用 javascript/jquery 从字符串中获取整数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10780087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:54:03  来源:igfitidea点击:

Getting Integer value from a String using javascript/jquery

javascriptjquery

提问by Kichu

These are the strings I have:

这些是我拥有的字符串:

"test123.00"
"yes50.00"

I want to add the 123.00 with 50.00.

我想用 50.00 添加 123.00。

How can I do this?

我怎样才能做到这一点?

I used the command parseInt() but it displays NaN error in alert box.

我使用了命令 parseInt() 但它在警告框中显示 NaN 错误。

This is the code:

这是代码:

 str1 = "test123.00";
 str2 = "yes50.00";
 total = parseInt(str1)+parseInt(str2);
 alert(total);

回答by Pranay Rana

just do this , you need to remove char other than "numeric" and "." form your string will do work for you

只需这样做,您需要删除“数字”和“。”以外的字符。形成你的字符串会为你工作

yourString = yourString.replace ( /[^\d.]/g, '' );

your final code will be

你的最终代码将是

  str1 = "test123.00".replace ( /[^\d.]/g, '' );
  str2 = "yes50.00".replace ( /[^\d.]/g, '' );
  total = parseInt(str1, 10) + parseInt(str2, 10);
  alert(total);

Demo

演示

回答by nunespascal

For parseInt to work, your string should have only numerical data. Something like this:

要使 parseInt 工作,您的字符串应该只有数字数据。像这样的东西:

 str1 = "123.00";
 str2 = "50.00";
 total = parseInt(str1)+parseInt(str2);
 alert(total);

Can you split the string before you start processing them for a total?

在开始处理它们之前,您可以拆分字符串吗?

回答by FosterZ

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);

working Jsfiddle

工作Jsfiddle

回答by Sanket

Is this logically possible??.. I guess the approach that you must take is this way :

这在逻辑上是可能的吗??.. 我想你必须采取的方法是这样的:

Str1 ="test123.00"
Str2 ="yes50.00"

This will be impossible to tackle unless you have delimiter in between testand 123.00

除非您在test和之间有分隔符,否则这是不可能解决的123.00

eg: Str1 = "test-123.00" 

Then you can split this way

那么你可以这样拆分

Str2 = Str1.split("-"); 

This will return you an array of words split with "-"

这将返回一个用“-”分割的单词数组

Then you can do parseFloat(Str2[1])to get the floating value i.e 123.00

然后你可以做得到parseFloat(Str2[1])浮动值即123.00