如何在JavaScript中将字符串转换为浮点数?

时间:2022-11-19 21:45:38

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?

我试图从datagrid中解析两个值。字段是数字的,当它们有逗号(例如,554,20)时,我不能在逗号之后得到数字。我尝试过parseInt和parseFloat。我该怎么做呢?

7 个解决方案

#1


296  

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

如果它们是一个单独的值(比如在法语中,1 / 2被写成0,5)

var value = parseFloat("554,20".replace(",", "."));

#2


41  

Have you ever tried to do this? :p

你试过这么做吗?: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(/,/,'.'));

#3


27  

Replace the comma with a dot.

用点替换逗号。

This will only return 554:

这将只返回554:

var value = parseFloat("554,20")

This will return 554.20:

这将返回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).

不要忘记parseInt()应该只用于解析整数(没有浮点数)。在你的情况下,它只会返回554。此外,在浮点数上调用parseInt()将不会围绕这个数字:它将占据它的底板(最近的低整数)。


Extended example to answer Pedro Ferreira's question from the comments:

用扩展的例子来回答Pedro Ferreira的问题:

If the textfield contains thousands separator dots like in 1.234.567,99 those could be eliminated beforehand with another replace:

如果textfield包含数千个分隔点(如1.234.567),那么99个可以用另一个替换来提前删除:

var fValue = parseFloat(document.getElementById("textfield").value.replace(/\./g,"").replace(",","."))

#4


13  

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"

#5


3  

@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:

@GusDeCool或者其他任何试图替换超过1000个分隔符的人,一种方法是使用regex全局替换:/foo/g。只要记住。是一个元字符,所以您必须转义它或将它放在括号中(\)。或[])。这里有一个选择:

var str = '6.000.000';
str.replace(/[.]/g,",");

#6


3  

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

#7


0  

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

我遇到了同样的问题,只是我事先不知道千位分隔符和小数分隔符是什么。我最后写了一个图书馆来做这件事。如果您对此感兴趣,它是:https://github.com/guillaumeleclerc/number解析

#1


296  

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

如果它们是一个单独的值(比如在法语中,1 / 2被写成0,5)

var value = parseFloat("554,20".replace(",", "."));

#2


41  

Have you ever tried to do this? :p

你试过这么做吗?: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(/,/,'.'));

#3


27  

Replace the comma with a dot.

用点替换逗号。

This will only return 554:

这将只返回554:

var value = parseFloat("554,20")

This will return 554.20:

这将返回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).

不要忘记parseInt()应该只用于解析整数(没有浮点数)。在你的情况下,它只会返回554。此外,在浮点数上调用parseInt()将不会围绕这个数字:它将占据它的底板(最近的低整数)。


Extended example to answer Pedro Ferreira's question from the comments:

用扩展的例子来回答Pedro Ferreira的问题:

If the textfield contains thousands separator dots like in 1.234.567,99 those could be eliminated beforehand with another replace:

如果textfield包含数千个分隔点(如1.234.567),那么99个可以用另一个替换来提前删除:

var fValue = parseFloat(document.getElementById("textfield").value.replace(/\./g,"").replace(",","."))

#4


13  

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"

#5


3  

@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:

@GusDeCool或者其他任何试图替换超过1000个分隔符的人,一种方法是使用regex全局替换:/foo/g。只要记住。是一个元字符,所以您必须转义它或将它放在括号中(\)。或[])。这里有一个选择:

var str = '6.000.000';
str.replace(/[.]/g,",");

#6


3  

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

#7


0  

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

我遇到了同样的问题,只是我事先不知道千位分隔符和小数分隔符是什么。我最后写了一个图书馆来做这件事。如果您对此感兴趣,它是:https://github.com/guillaumeleclerc/number解析