How to convert a currency string to a double with jQuery or Javascript?

后端 未结 19 2773
天涯浪人
天涯浪人 2020-11-22 17:30

I have a text box that will have a currency string in it that I then need to convert that string to a double to perform some operations on it.

\"$1,1

19条回答
  •  礼貌的吻别
    2020-11-22 17:47

    This worked for me and covers most edge cases :)

    function toFloat(num) {
      const cleanStr = String(num).replace(/[^0-9.,]/g, '');
      let dotPos = cleanStr.indexOf('.');
      let commaPos = cleanStr.indexOf(',');
    
      if (dotPos < 0) dotPos = 0;
    
      if (commaPos < 0) commaPos = 0;
    
      const dotSplit = cleanStr.split('.');
      const commaSplit = cleanStr.split(',');
    
      const isDecimalDot = dotPos
        && (
          (commaPos && dotPos > commaPos)
          || (!commaPos && dotSplit[dotSplit.length - 1].length === 2)
        );
    
      const isDecimalComma = commaPos
        && (
          (dotPos && dotPos < commaPos)
          || (!dotPos && commaSplit[commaSplit.length - 1].length === 2)
        );
    
      let integerPart = cleanStr;
      let decimalPart = '0';
      if (isDecimalComma) {
        integerPart = commaSplit[0];
        decimalPart = commaSplit[1];
      }
      if (isDecimalDot) {
        integerPart = dotSplit[0];
        decimalPart = dotSplit[1];
      }
    
      return parseFloat(
        `${integerPart.replace(/[^0-9]/g, '')}.${decimalPart.replace(/[^0-9]/g, '')}`,
      );
    }
    
    
    toFloat('USD 1,500.00'); // 1500
    toFloat('USD 1,500'); // 1500
    toFloat('USD 500.00'); // 500
    toFloat('USD 500'); // 500
    
    toFloat('EUR 1.500,00'); // 1500
    toFloat('EUR 1.500'); // 1500
    toFloat('EUR 500,00'); // 500
    toFloat('EUR 500'); // 500
    

提交回复
热议问题