Convert String with Dot or Comma as decimal separator to number in JavaScript

后端 未结 11 726
时光取名叫无心
时光取名叫无心 2020-12-03 04:26

An input element contains numbers a where comma or dot is used as decimal separator and space may be used to group thousands like this:

\'1,2\'

相关标签:
11条回答
  • 2020-12-03 04:43

    Here is my solution that doesn't have any dependencies:

    return value
      .replace(/[^\d\-.,]/g, "")   // Basic sanitization. Allows '-' for negative numbers.
      .replace(",", ".")           // Change all commas to periods.
      .replace(/\.(?=.*\.)/g, ""); // Remove all periods except the last one.
    

    (I left out the conversion to a number - that's probably just a parseFloat call if you don't care about JavaScript's precision problems with floats.)

    The code assumes that:

    • Only commas and periods are used as decimal separators. (I'm not sure if locales exist that use other ones.)
    • The decimal part of the string does not use any separators.
    0 讨论(0)
  • 2020-12-03 04:44

    I realise I'm late to the party, but I wanted a solution for this that properly handled digit grouping as well as different decimal separators for currencies. As none of these fully covered my use case I wrote my own solution which may be useful to others:

    function parsePotentiallyGroupedFloat(stringValue) {
        stringValue = stringValue.trim();
        var result = stringValue.replace(/[^0-9]/g, '');
        if (/[,\.]\d{2}$/.test(stringValue)) {
            result = result.replace(/(\d{2})$/, '.$1');
        }
        return parseFloat(result);
    }
    

    This should strip out any non-digits and then check whether there was a decimal point (or comma) followed by two digits and insert the decimal point if needed.

    It's worth noting that I aimed this specifically for currency and as such it assumes either no decimal places or exactly two. It's pretty hard to be sure about whether the first potential decimal point encountered is a decimal point or a digit grouping character (e.g., 1.542 could be 1542) unless you know the specifics of the current locale, but it should be easy enough to tailor this to your specific use case by changing \d{2}$ to something that will appropriately match what you expect to be after the decimal point.

    0 讨论(0)
  • 2020-12-03 04:45

    You could replace all spaces by an empty string, all comas by dots and then parse it.

    var str = "110 000,23";
    var num = parseFloat(str.replace(/\s/g, "").replace(",", "."));
    console.log(num);
    

    I used a regex in the first one to be able to match all spaces, not just the first one.

    0 讨论(0)
  • 2020-12-03 04:45

    From number to currency string is easy through Number.prototype.toLocaleString. However the reverse seems to be a common problem. The thousands separator and decimal point may not be obtained in the JS standard.

    In this particular question the thousands separator is a white space " " but in many cases it can be a period "." and decimal point can be a comma ",". Such as in 1 000 000,00 or 1.000.000,00. Then this is how i convert it into a proper floating point number.

    var price = "1 000.000,99",
        value = +price.replace(/(\.|\s)|(\,)/g,(m,p1,p2) => p1 ? "" : ".");
    console.log(value);

    So the replacer callback takes "1.000.000,00" and converts it into "1000000.00". After that + in the front of the resulting string coerces it into a number.

    This function is actually quite handy. For instance if you replace the p1 = "" part with p1 = "," in the callback function, an input of 1.000.000,00 would result 1,000,000.00

    0 讨论(0)
  • 2020-12-03 04:47

    This is the best solution

    http://numeraljs.com/

    numeral().unformat('0.02'); = 0.02
    
    0 讨论(0)
  • 2020-12-03 04:47

    What about:

    parseFloat(str.replace(' ', '').replace('.', '').replace(',', '.'));
    
    0 讨论(0)
提交回复
热议问题