le0
le0

Reputation: 851

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

Upvotes: 5

Views: 1532

Answers (2)

Hugo Gresse
Hugo Gresse

Reputation: 17899

⚠️ 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.

Upvotes: 8

Doug Stevenson
Doug Stevenson

Reputation: 317402

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))

Upvotes: 7

Related Questions