admin管理员组文章数量:1129016
I am trying to parse two values from a datagrid. The fields are numeric, and when they have a comma (ex. 554,20), I can't get the numbers after the comma. I've tried parseInt
and parseFloat
. How can I do this?
I am trying to parse two values from a datagrid. The fields are numeric, and when they have a comma (ex. 554,20), I can't get the numbers after the comma. I've tried parseInt
and parseFloat
. How can I do this?
- see also: stackoverflow.com/questions/24318654 – dreftymac Commented Jun 20, 2014 at 1:42
9 Answers
Reset to default 442If they're meant to be separate values, try this:
var values = "554,20".split(",")
var v1 = parseFloat(values[0])
var v2 = parseFloat(values[1])
If they're meant to be a single value (like in French, where one-half is written 0,5)
var value = parseFloat("554,20".replace(",", "."));
Have you ever tried to do this? :p
var str = '3.8';ie
alert( +(str) + 0.2 );
+(string) will cast string into float.
Handy!
So in order to solve your problem, you can do something like this:
var floatValue = +(str.replace(/,/,'.'));
Replace the comma with a dot.
This will only return 554:
var value = parseFloat("554,20")
This will return 554.20:
var value = parseFloat("554.20")
So in the end, you can simply use:
var fValue = parseFloat(document.getElementById("textfield").value.replace(",","."))
Don't forget that parseInt()
should only be used to parse integers (no floating points). In your case it will only return 554. Additionally, calling parseInt() on a float will not round the number: it will take its floor (closest lower integer).
Extended example to answer Pedro Ferreira's question from the comments:
If the textfield contains thousands separator dots like in 1.234.567,99
those could be eliminated beforehand with another replace
:
var fValue = parseFloat(document.getElementById("textfield").value.replace(/\./g,"").replace(",","."))
If you extend String object like this..
String.prototype.float = function() {
return parseFloat(this.replace(',', '.'));
}
.. you can run it like this
"554,20".float()
> 554.20
works with dot as well
"554.20".float()
> 554.20
typeof "554,20".float()
> "number"
@GusDeCool or anyone else trying to replace more than one thousands separators, one way to do it is a regex global replace: /foo/g
. Just remember that .
is a metacharacter, so you have to escape it or put it in brackets (\.
or [.]
). Here's one option:
var str = '6.000.000';
str.replace(/[.]/g,",");
You can use this function. It will replace the commas with ' ' and then it will parseFlaot the value and after that it will again adjust the commas in value.
function convertToFloat(val) {
if (val != '') {
if (val.indexOf(',') !== -1)
val.replace(',', '');
val = parseFloat(val);
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
}
}
return val;
}
If someone is looking for a way to parse float from an arbitrary string,
it can be done like that:
function extractFloat(text) {
const match = text.match(/\d+((\.|,)\d+)?/)
return match && match[0]
}
extractFloat('some text with float 5.25') // 5.25
Try
let str ="554,20";
let float = +str.replace(',','.');
let int = str.split(',').map(x=>+x);
console.log({float,int});
I had the same problem except I did not know in advance what were the thousands separators and the decimal separator. I ended up writing a library to do this. If you are interested it here it is : https://github.com/GuillaumeLeclerc/number-parsing
本文标签: parsingHow to convert string into float in JavaScriptStack Overflow
版权声明:本文标题:parsing - How to convert string into float in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736720165a1949422.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论