❯ehsan.blog
~/blog/your-test-says-1-234-does-not-equal-1-234 — zsh
❯cat your-test-says-1-234-does-not-equal-1-234.md

Your test says 1 234 does not equal 1 234

·9 min read

Your test says 1 234 does not equal 1 234 — article card for a post by Ehsan Shahid

A price test started failing and the failure message made no sense:

plaintext
Expected values to be strictly equal:

'1 234' !== '1 234'

That is the real output of assert.strictEqual, copied out of my terminal. Two strings. Same five characters, as far as anyone can see. Same length. Node says they are not equal, and Node is right.

I stared at that for longer than I would like to admit. I checked for trailing spaces. I retyped the expected value by hand. I rewrote the test. The message kept coming back identical, which is the worst possible thing a failure message can do, because it quietly tells you the bug is in your eyes.

The test was this boring:

js
import assert from 'node:assert'

const price = new Intl.NumberFormat('fr-FR').format(1234)

assert.strictEqual(price, '1 234')

The character you cannot see

The space in the formatted number is not a space. It is U+202F, the narrow no-break space. The one I typed in my test file is U+0020, the one under your thumb.

Ask the string directly and it tells you straight away:

js
const price = new Intl.NumberFormat('fr-FR').format(1234)

console.log([...price].map((c) => c.codePointAt(0).toString(16)))
// [ '31', '202f', '32', '33', '34' ]

There it is, sitting between the 1 and the 2. Every other character is an ordinary digit. One character in the middle is something else entirely, and no amount of looking at it in a terminal will ever show you that, because its entire job is to look like a space.

It is not a bug and nobody typed it by accident. It comes from CLDR, the shared locale database that Node, your browser and basically everything else use to answer questions like “how do French people write large numbers”. The answer CLDR gives for French is: group the digits with a narrow no-break space. The no-break half is the point — it stops a browser from breaking 1 234 across two lines and leaving a lonely 234 at the start of the next one. It is a small, thoughtful piece of typography that has been quietly ruining string comparisons for years.

And it is not only French. Different locales reach for different invisible characters:

js
const seen = (loc) =>
  new Intl.NumberFormat(loc)
    .formatToParts(1234567)
    .filter((p) => p.type === 'group')
    .map((p) => 'U+' + p.value.codePointAt(0).toString(16).toUpperCase().padStart(4, '0'))[0]

for (const loc of ['en-US', 'de-DE', 'fr-FR', 'ru-RU', 'sv-SE', 'pl-PL', 'ar-EG']) {
  console.log(loc, seen(loc))
}
// en-US U+002C   a comma
// de-DE U+002E   a full stop
// fr-FR U+202F   narrow no-break space
// ru-RU U+00A0   no-break space
// sv-SE U+00A0   no-break space
// pl-PL U+00A0   no-break space
// ar-EG U+066C   Arabic thousands separator

Three of those look like a space in your editor and none of them are one. Russian, Swedish and Polish use U+00A0, which is a different invisible character from the French one. So a fix that handles French does not automatically handle Swedish, and you will not find that out by reading the code.

One more, because it caught me later in the same afternoon. A French currency string uses both:

js
const eur = new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(1234.5)
// '1\u202f234,50\u00a0€'

I have written the two invisible characters as escapes there so you can see them. In a real console you see 1 234,50 € and you would never guess the two gaps are different characters. U+202F groups the digits, U+00A0 holds the euro sign against the number.

The fix that silently gives you the wrong number

Here is where this stops being a trivia question and starts costing money.

The normal reaction, once you know a space is in the way, is to take the space out and parse what is left:

js
const price = new Intl.NumberFormat('fr-FR').format(1234.5)   // '1\u202f234,5'

const value = parseFloat(price.replace(/ /g, '').replace(',', '.'))

console.log(value)
// 1

Not 1234.5. Not NaN. One.

That replace(/ /g, '') looks for the ordinary space, finds none, and changes nothing. So parseFloat gets handed 1\u202f234,5, reads the leading 1, hits a character that cannot be part of a number, and stops there. parseFloat never throws. Stopping early is its documented job. It returns 1, a perfectly valid number, and your code carries on with it.

If you had reached for Number() instead you would at least have got NaN, which is ugly but loud. parseFloat hands you a plausible, round, completely wrong figure and says nothing. A product priced at 1 234,50 € goes through your pipeline as 1. That is the kind of bug that gets discovered by an accountant.

So use \s, and watch that break too

The real character class for “any whitespace” is \s, and it does cover both of the space-like separators:

js
/\s/.test('\u202f')   // true   — narrow no-break space
/\s/.test('\u00a0')   // true   — no-break space

const price = new Intl.NumberFormat('fr-FR').format(1234.5)
parseFloat(price.replace(/\s/g, '').replace(',', '.'))
// 1234.5

That works. For French, Russian, Swedish, Polish and every other locale whose separator happens to be a kind of space.

It does not work for Arabic:

js
/\s/.test('\u066c')   // false

U+066C, the Arabic thousands separator, is not whitespace by any definition. It is a punctuation mark that happens to do the same job. So the \s version of the fix is not wrong so much as it is locale-shaped: it handles the locales you thought about while writing it, and quietly fails on the next one somebody adds. Which is the same shape as the original bug, one layer further down.

You can keep patching the regular expression. I did, for about ten minutes, before noticing I was writing a worse copy of a database that already ships with Node.

What to actually do

The honest fix is to stop round-tripping. A formatted number is output. It is a decision about how to show a value to a particular human in a particular country, and it is lossy in exactly the way a rendered thing is allowed to be. Parsing it back is asking a photograph for the camera settings.

Keep the number. In almost every case where I have hit this, the original value was still sitting right there a few lines up, and somebody had reached for the formatted string because it was the variable closest to hand.

js
const amount = 1234.5                                           // keep this
const display = new Intl.NumberFormat('fr-FR').format(amount)   // show this

Do your arithmetic, your comparisons and your sorting on amount. Send amount to your API. Store amount. display goes into the DOM and nowhere else.

In tests, compare numbers or be explicit. If you are testing your own formatting logic rather than the behaviour of CLDR, turn the grouping off and the invisible character disappears with it:

js
new Intl.NumberFormat('fr-FR', { useGrouping: false }).format(1234.5)
// '1234,5'

If you really are asserting on a grouped string, write the separator as an escape so the next person can see what they are looking at:

js
assert.strictEqual(new Intl.NumberFormat('fr-FR').format(1234), '1\u202f234')

That passes, and it does not lie about what is in the string. Be aware you are now asserting on CLDR data that can legitimately change between Node versions — French itself moved from U+00A0 to U+202F in an earlier CLDR release. Pinning a test to it is a choice, not an accident, and worth a comment saying so.

If you genuinely must parse user-typed numbers, parse them against the locale rather than against a regular expression you wrote from memory. formatToParts will tell you exactly which characters that locale uses for groups and decimals, so you can strip the right ones instead of the ones you guessed:

js
const partsFor = (loc) => {
  const parts = new Intl.NumberFormat(loc).formatToParts(1234.5)
  return {
    group: parts.find((p) => p.type === 'group').value,
    decimal: parts.find((p) => p.type === 'decimal').value,
  }
}

console.log(partsFor('fr-FR'))
// { group: '\u202f', decimal: ',' }
console.log(partsFor('ar-EG'))
// { group: '\u066c', decimal: '\u066b' }

(Those two comments show the separators as escapes again, for the same reason as before. A real console.log prints the characters themselves, which is to say it prints almost nothing.)

Ask the runtime what the separators are, then remove those. It is a few more lines than a regular expression and it is right in every locale, including the ones you have not heard of yet.

How to spot this in your own code in five minutes

Grep for toLocaleString and NumberFormat, then look at what happens to the result:

  1. Does it get compared to a string literal? if (row.total === '1 234') is already broken for most of Europe.
  2. Does it get parsed back? parseFloat(formatted), Number(formatted), formatted.replace(...) — any of these means a display string has been promoted back into a value, and that is the moment to go find the original number.
  3. Does it end up in a URL, a form field or a database column? Formatted numbers should never reach any of those. If one does, every consumer downstream now has to guess which country it came from.

And if you are ever staring at two values that print identically but refuse to be equal, this is the one-liner that ends the argument:

js
console.log([...value].map((c) => c.codePointAt(0).toString(16)))

It works for this bug, for the non-breaking spaces a designer pastes out of Figma, for the zero-width characters that ride along with text copied from a PDF, and for the smart quotes a word processor swaps in behind your back. It costs one line and it has never once failed to tell me the truth.

What I took from it

The failure message was the whole lesson. '1 234' !== '1 234' is not a confusing error — it is a precise one, describing a situation where the thing your terminal draws and the thing in memory are not the same thing. I lost half an hour because I trusted the drawing.

Everything after that followed from one assumption worth naming: that a formatted number is still a number. It is not. It is a sentence about a number, written for a reader in a particular place, and the moment you try to do arithmetic on the sentence instead of the number, something will go wrong politely.

It belongs to the same family as your query string saying page=undefined, an object reordering itself the moment its keys are numbers, and one leading slash deleting half your API base URL: small, documented, entirely correct behaviour, landing in a place where the surrounding code quietly assumed something simpler.

Tested on Node 22.16. The separators come from CLDR, so your runtime’s version decides the exact characters — run the formatToParts snippet above and let it tell you rather than trusting mine.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.