格式化为货币样式字符串的数字返回值不等于预期值。
const expected = `12,09 €`;
const formatted =
new Intl.NumberFormat(`de-De`, { style: `currency`, currency: `EUR` }).format(12.09);
expect(formatted).toEqual(expected); // Fail
expected === formatted; // false
// Logged values
console.log(`FORMATTED: type = ${typeof formatted}, value = '${actual}';`);
console.log(`EXPECTED: type = ${typeof expected}, value = '${expected}';`);
// FORMATTED: type = string, value = '12,09 €';
// EXPECTED: type = string, value = '12,09 €';
但是
new Intl.NumberFormat(`de-De`, { style: `currency`, currency: `EUR` }).format(12.09);
// returns "12,09 €"
`12,09 €` === `12,09 €`; // true
typeof formatted; // "string"
问题:为什么两个相似的字符串不相等?
最佳答案
Intl.NumberFormat
返回具有不间断空格(160 个字符代码)的字符串,而您的预期
字符串具有正常空格(32 个字符代码)。
expected[5] === 格式化[5]
//false
看看这个线程:https://github.com/nodejs/node/issues/24674
我认为您可以简单地使用 replace
函数解决这个问题。如:
const expected = `12,09 €`.replace(/\s/, String.fromCharCode(160));
const formatted =
new Intl.NumberFormat(`de-De`, {
style: `currency`,
currency: `EUR`
}).format(12.09);
console.log(expected === formatted);
(提示:将其提取到一个单独的函数中是个好主意,该函数将字符串标准化为空格)
关于javascript - 相同字符串值的两个实例不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55335550/