Skip to content
This repository was archived by the owner on Apr 14, 2021. It is now read-only.

NumberFormat.formatToParts does not work. #296

Closed
jstafford opened this issue Nov 29, 2017 · 1 comment
Closed

NumberFormat.formatToParts does not work. #296

jstafford opened this issue Nov 29, 2017 · 1 comment

Comments

@jstafford
Copy link
Contributor

TL;DR: Due to Line 441 in 11.numberformat.js formatToParts is useless for any real world use.

Long version:

When I try to use formatToParts to break up a string such as "123,456" I get:
"[{"type":"nan","value":"NaN"}]". The expected result is "[{"type":"integer","value":"123"},{"type":"group","value":","},{"type":"integer","value":"456"}]"

Sample code:

const numberFormater = new IntlPolyfill.NumberFormat()
const formattedValue = numberFormater.format(123456)
const parts = numberFormater.formatToParts(formattedValue)
console.log(JSON.stringify(parts))

Looking at the implementation of formatToParts we see:

function formatToParts(value = undefined) {
  let internal = this !== null && typeof this === 'object' && getInternalProperties(this);
  if (!internal || !internal['[[initializedNumberFormat]]'])
      throw new TypeError('`this` value for formatToParts() is not an initialized Intl.NumberFormat object.');

  let x = Number(value);
  return FormatNumberToParts(this, x);
}

Stepping through this code, when Number("123,456") executes, the result is Number.NaN. From this point on, all the logic in FormatNumberToParts has no hope of working.

The fix is to delete this line, and pass value to FormatNumberToParts.

If you would like me to submit a pull request I can do that if it makes things easier.

I would like to use formatToParts in a project I am working on, so if you could fix this and do a new release soon I would really appreciate it.

jstafford added a commit to jstafford/Intl.js that referenced this issue Nov 29, 2017
@jstafford
Copy link
Contributor Author

Well color me confused. I was sure that formatToParts took the formatted string, not the original number. My mistake. Sincere apologies.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant