Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native .toLocaleString() not working on android

Tags:

react-native

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

like image 888
EQuimper Avatar asked Dec 31 '16 11:12

EQuimper


3 Answers

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:+'
like image 54
Taylor Johnson Avatar answered Oct 09 '22 06:10

Taylor Johnson


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.

like image 24
Dani Akash Avatar answered Oct 09 '22 06:10

Dani Akash


You can use

number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
like image 15
Tamir Haim Rabia Avatar answered Oct 09 '22 06:10

Tamir Haim Rabia