admin 管理员组文章数量: 1086019
I know that we can extract an integer value from a string using
var x = "> 1";
x = parseInt(x.match(/\d+/)[0], 10));
How do I get a float value from a string
example: var x = "> 1.1"
I know we can just use x.substring(2);
But for a more generic solution? since the above will not give the accurate result for
var x = "1.1"
So what is the best way to extract the float value 1.1
from
var x = "> 1.1"
I know that we can extract an integer value from a string using
var x = "> 1";
x = parseInt(x.match(/\d+/)[0], 10));
How do I get a float value from a string
example: var x = "> 1.1"
I know we can just use x.substring(2);
But for a more generic solution? since the above will not give the accurate result for
var x = "1.1"
So what is the best way to extract the float value 1.1
from
var x = "> 1.1"
Share
Improve this question
edited Feb 7, 2014 at 18:27
user544079
asked Feb 7, 2014 at 18:15
user544079user544079
16.6k42 gold badges120 silver badges172 bronze badges
1
-
1
How about
/\d+\.?\d*/
– Matt Burland Commented Feb 7, 2014 at 18:18
4 Answers
Reset to default 5Use parseFloat
and a regular expression that matches a number with optional decimals and minus sign.
var f = parseFloat(x.match(/-?(?:\d+(?:\.\d*)?|\.\d+)/)[0]);
You can try the following one to extract only numbers like floating or integer as an array as many as you want using the match function.
str = 'On schedule: 3243.8 miles away (4491 minutes)';
values = str.match(/[0-9.]+/g); //=> ["3243.8", "4491"]
x = parseFloat(x.match(/[-+]?([0-9]*\.[0-9]+|[0-9]+)/));
Use parseFloat(). It does exactly what you're looking for.
本文标签: jqueryextract a float from a string in javascriptStack Overflow
版权声明:本文标题:jquery - extract a float from a string in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744045609a2524058.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论