Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 577
le0 Avatar asked Feb 27 '18 15:02

le0


2 Answers

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

like image 140
Hugo Gresse Avatar answered Nov 15 '22 04:11

Hugo Gresse


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))
like image 23
Doug Stevenson Avatar answered Nov 15 '22 02:11

Doug Stevenson