react-native .toLocaleString() not working on android

I'm using .toLocaleString() on react-native for my number output. All work on IOS but seems not working on Android. This is normal or? Do I need to use a function for the decimal?

enter image description here


Solution 1:

rather than using a polyfill or an external dependency, change the JSC your android app builds with. For the newer versions of react-native add or override the following line in app/build.gradle

def jscFlavor = 'org.webkit:android-jsc-intl:+'

Solution 2:

This is an issue with Javascript core used to run react native in Android and not with react native itself. To overcome this, you'll have to integrate latest javascript core into your android build or upgrade react native to 0.59.

The details are documented in JSC Android Buildscripts repo.

Now for people who would like to do the locale string formatting without needing to integrate the entire javascript core, Javascript has Internationalization API which lets you format numbers to language sensitive format. Documentation available at MDN

This API is not available in android and needs to be polyfilled using Intl

In your project root, install the Intl library

yarn add intl

And then in your project's index file (index.js) add the following code at the top of the file:

if(Platform.OS === 'android') { // only android needs polyfill
  require('intl'); // import intl object
  require('intl/locale-data/jsonp/en-IN'); // load the required locale details
}

After doing the above two steps, you can now get locale string anywhere in your project using

new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(10000000);

In case you need to format number for another locale code, all the locale code details are available under the intl/locale-data/jsonp/ directory. Simply require the ones you need in your index.js file.

Solution 3:

You can use

number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")

Solution 4:

On newer versions of RN >0.62 you can change the JSC (JavaScriptCore) build variant to support/include ICU i18n library and necessary data allowing to use e.g. Date.toLocaleString and String.localeCompare

Replace this line in your android/app/build.gradle file

def jscFlavor = 'org.webkit:android-jsc:+'

with this line

def jscFlavor = 'org.webkit:android-jsc-intl:+'

Clean build and react-native run android

Note

This variant is about 6MiB larger per architecture than default. So, expect your APK size to increase by about 4MB for each APK architecture build if using def enableSeparateBuildPerCPUArchitecture = true and a more bigger APK if separate build per architecture is disabled