Bas*_*sin 2 javascript jasmine typescript
格式化为货币样式字符串的数字返回的值不等于预期值。
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 €';
Run Code Online (Sandbox Code Playgroud)
但
new Intl.NumberFormat(`de-De`, { style: `currency`, currency: `EUR` }).format(12.09);
// returns "12,09 €"
`12,09 €` === `12,09 €`; // true
typeof formatted; // "string"
Run Code Online (Sandbox Code Playgroud)
问题:为什么两个相似的字符串不相等?
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);Run Code Online (Sandbox Code Playgroud)
(提示:最好将它提取到一个单独的函数,该函数接受一个字符串和一个规范化空格)
| 归档时间: |
|
| 查看次数: |
171 次 |
| 最近记录: |