简体   繁体   中英

Wrong localisation in Firebase Cloud Function

When executed in firebase cloud functions, the following command returns the American format instead of the localised one. However, it works well in browsers.

price.toLocaleString("pt-BR", {
  maximumFractionDigits: 2
});

Is there any way toLocaleString() works properly in firebase cloud functions?

Update:

let price = 1456.21
let formattedPrice = price.toLocaleString("pt-BR", {maximumFractionDigits: 2});

//Value of formattedPrice expected: 1.456,21 (it works in browsers).
//Value of formattedPrice returned in Firebase Cloud Functions: 1,456.21

Maybe it something related to the default ICU of Node (--with-intl=small-icu). To support internationalization, it seems the value should be --with-intl=full-icu.

https://nodejs.org/api/intl.html#intl_options_for_building_node_js

⚠️ intl seems no longer active/supported (last version is 4yo...).

I've achieved adding the real intl as follow:

  1. Add full-icu dependencies on your Firebase Cloud Functions: npm install full-icu --save
  2. Edit you functions (after a successful deployment) on console.cloud.google.com (don't forget to select the right google dev project)
  3. Add NODE_ICU_DATA env var with value node_modules/full-icu
  4. Save and wait 1 or 2 min for the functions to be deploy.

Furter update will not remove this env, and I was able to use Intl apis from Luxon successfully.

You shouldn't depend on special flags for building the version of node used in Cloud Functions. What you can do instead is pull in a module that deals with formatting locale strings. For example, you can use the intl module:

npm install intl

The use this:

const intl = require('intl')
const format = intl.NumberFormat("pt-BR", {maximumFractionDigits: 2})
console.log(format.format(price))

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