简体   繁体   中英

NumberFormat returning wrong format for converting number to currency

Code:

 let currency = 400023; console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(currency));

Expected: €400.023,00

Actual: €400,023.00

On the examples I found in the JS documentation, it shows dots being used as thousand separators and commas for cents, yet when I use it myself it doesn't work.

As @RobG pointed out it's an issue with your JS implementation, which isn't supporting the Intl object properly.

All current browsers have full support for Intl.

If you running your code on Node.js the situation is a little bit more complicated. Before Node.js 13, there was only partial support for internationalization (ICU) including Intl.

Starting with Node.js 13 there is full ICU/internationalization support built in by default. For details see:

Essentialy, you can run this piece of code:

 console.log(new Intl.DateTimeFormat('es',{month:'long'}).format(new Date(9E8)));

Your output might be:

  • Error: No support for ICU - very old browser / Node.js
  • January: Partial support for ICU - old browser / Node.js < 13
  • enero: Full support for ICU - recent browser / Node.js >= 13

In case your stuck with Node.js < 13, you can backfill full ICU support with https://www.npmjs.com/package/full-icu .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM