我正在使用 javascript,我已经看到了一些将货币转换为数字的方法,但没有一种能够灵活地理解多种输入格式(小数分隔符根据用户偏好进行更改)。
让我表明我的意思:
一些可能的输入(字符串或数字):
输出(数量):
您可以检查输入是数字还是字符串。如果是数字,则立即返回。如果是字符串,则检测数字格式并根据需要替换字符,然后返回转换后的数字。
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; }