如何将货币转换为数字?

问题描述 投票:0回答:1

我正在使用 javascript,并且我已经看到了一些将货币转换为数字的方法,但没有一种能够灵活地理解多种输入格式(小数分隔符根据用户偏好进行更改)。

让我表明我的意思:

一些可能的输入(字符串或数字):

  • “1.000,50”
  • “1.000,50 美元”
  • “1,000.50”
  • “1,000.50 美元”
  • 1000.50

输出(数量):

  • 1000.50
javascript type-conversion number-formatting currency-formatting
1个回答
0
投票

您可以检查输入是数字还是字符串。如果是数字,则立即返回。如果是字符串,则检测数字格式并根据需要替换字符,然后返回转换后的数字。

const inputs = [
  "1.000,50",
  "$1.000,50",
  "1,000.50",
  "$1,000.50",
  1000.50
];

const expected = 1000.50;

const convert = (input) => {
  if (typeof input === 'number') return input; // Pass-through
  if (typeof input !== 'string')
    throw new Error(`Expected number or string for '${input}' (${typeof input})`);
  const stripped = input.replace(/[^\d.,]/g, '')
  return stripped.slice(-3).includes(',')
    ? +stripped.replace(/\./g, '').replace(/,/g, '.') // e.g. French format
    : +stripped.replace(/\,/g, '');                   // e.g. US format
};

// true
console.log(inputs.map(convert).every(actual => actual - expected < 0.000001));
.as-console-wrapper { top: 0; max-height: 100% !important; }

© www.soinside.com 2019 - 2024. All rights reserved.