格式化为货币样式字符串的数字返回的值不等于预期值。
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个字符代码)的expected
字符串,而您的字符串具有一个普通空格(32个字符代码)。
expected[5] === formatted[5]
//错误
看一下这个线程: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);
(提示:将其提取到一个单独的函数中是一个好主意,该函数将字符串归一化空格)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句