313

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?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345

9 Answers9

433

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)

var value = parseFloat("554,20".replace(",", "."));
Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102
  • 6
    What about where you have a comma used as a thousand seperator? E.g. 1234 written as 1,234 – Chris B Jun 26 '09 at 10:33
  • 6
    You could just remove the comma, then parse it. (eg. replace it with "") – Jesse Rusak Jun 30 '09 at 11:25
  • 7
    it's not very safe, as sconto = parseFloat("5,,5".replace(",", ".")); returns 5 leading one to believe it's a valid number, but you loose the .5 part or you could consider it is not a valid number – max4ever Apr 01 '11 at 09:02
  • 1
    @max4ever If you're worried about silently accepting invalid numbers, you can use ```+(string)``` instead of ```parseString(string)``` as suggested by @Stev below. So, the first example would be ```v1 = +(values[0]); v2 = +(values[1]);```. – Jesse Rusak Nov 08 '12 at 02:10
  • 1
    FAIL, what if my number is `6.000.000`. Function replace only replace first comma separator – GusDeCooL Sep 17 '13 at 23:41
  • Use a regex as the first param with the `g` flag in order to do a global replace on the string. e.g. `string.replace(/,/g, '.')`. – mAAdhaTTah Jan 20 '17 at 19:16
  • I hate the manual hack of replacing `,` with `.`. Couldn't `parseFloat` take a *locale* parameter instead? – Stef Dec 01 '21 at 14:58
62

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(/,/,'.'));
Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Stev
  • 637
  • 5
  • 3
  • 8
    I really like the `+(str)` solution - `parseFloat` ignores invalid characters after the number, `+(str)` returns `NaN` in those cases, which is exactly what I need. – Alex May 28 '12 at 12:25
47

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(",","."))
mit
  • 11,083
  • 11
  • 50
  • 74
Wadih M.
  • 12,810
  • 7
  • 47
  • 57
17

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"
sobi3ch
  • 2,555
  • 2
  • 31
  • 41
  • 10
    Although usually it's considered bad form to modify the base object prototypes. What if another framework also tried to do that but the functionality differed? – phreakhead Jan 22 '13 at 01:02
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:

var str = '6.000.000';
str.replace(/[.]/g,",");
Nick Benes
  • 1,334
  • 15
  • 14
2

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;
    }
Muhammad Bilal
  • 125
  • 1
  • 9
2

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
Code4Art
  • 741
  • 8
  • 9
1

Try

let str ="554,20";
let float = +str.replace(',','.');
let int = str.split(',').map(x=>+x);

console.log({float,int});
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
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

DARK_DUCK
  • 1,727
  • 2
  • 12
  • 22