0

I am working with some rather large integers, and need to add some decimals to the number. I am using the Intl.NumberFormat('en-US') to place the decimals in the needed place.

That part is working, but after formatting the number, Javascript no longer recognizes it as a valid number.

    let numbform = new Intl.NumberFormat('en-US');
    console.log("value: ", value); // -765776.6480749019
    let test = numbform.format(Number(parseFloat(Number(value).toFixed(Number(arg)))))
    console.log("numberform: ", test); // -765,776.648
    console.log("typeof: ", typeof test); // string
    console.log("Number(test): ", Number(test)); // NaN

i am guessing it has to do with the extra decimals, but i have honestly no idea how to keep the precision, and 'reverse', the NumberFormat functionality.

  • 1
    It's because of the comma. If you want to convert the string `"-765,776.648"` back into a number, remove the comma(s) first: `Number(text.replace(/,/g, ""))`. – T.J. Crowder Nov 14 '22 at 10:53
  • It's not the extra *decimals*, it's the thousand separator `,` which cannot be properly parsed. More generally, `Number` does not parse from localised format because it cannot know which one is it - for example, if you had `123,456` is that comma a *thousand* separator or a *decimal* separator? Just by looking at the string, it's impossible to figure out, depends on the culture it was used when formatting. – VLAZ Nov 14 '22 at 10:53
  • @T.J.Crowder which works only for some cultures. For example, the same number formatted for a different culture might end up as `"-765.776,648"` at which point the conversion with removing commas is several orders of magnitude off. – VLAZ Nov 14 '22 at 10:54
  • There's also no point in passing the result of calling `parseFloat` into `Number`. `parseFloat` always returns a number. – T.J. Crowder Nov 14 '22 at 10:55
  • @VLAZ - Yes, that's true if they're working on something that will be used in a variety of locales, but the `'en-US'` suggests the thousands separator will be `,`. If they need to support locales where that's not the case, they'll need to remove locale-specific thousands separators and convert the locale-specific decimal separator to `.` if necessary (because `Number` only understands `.`, specifically, as a decimal separator). – T.J. Crowder Nov 14 '22 at 10:56

0 Answers0