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

后端 未结 11 771
时光取名叫无心
时光取名叫无心 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.

提交回复
热议问题