react-native .toLocaleString() not working on android - react-native

Updated 2022: With hermes enabled you should be good now.
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?

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:+'

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

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

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.

The reason for this is very old version of JavaScriptCore used by react-native. iOS embeds own version which is why it is working fine there.
Issue still exists (some reading about where it's heading https://github.com/facebook/react-native/issues/19737)
And more info about this from Airbnb devs
https://medium.com/airbnb-engineering/react-native-at-airbnb-the-technology-dafd0b43838 (search for "JavaScriptCore inconsistencies")

(value) => {
if (typeof value === 'number') {
const [currency, cents] = (value / 100).toFixed(2).toString().split('.');
return `${currency.replace(/\B(?=(\d{3})+(?!\d))/g, '.')},${cents}`;
}
return '0,00';
}

it's more recent and lightweight, please check
First install:
yarn add #formatjs/intl-getcanonicallocales #formatjs/intl-locale #formatjs/intl-pluralrules #formatjs/intl-numberformat
Check if need polyfill
import {shouldPolyfill} from '#formatjs/intl-numberformat/should-polyfill'
if (shouldPolyfill()) {
require('#formatjs/intl-getcanonicallocales/polyfill');
require('#formatjs/intl-locale/polyfill');
require('#formatjs/intl-pluralrules/polyfill');
require('#formatjs/intl-numberformat/polyfill');
require('#formatjs/intl-numberformat/locale-data/en-US');
}
see source: https://formatjs.io/docs/polyfills/intl-numberformat/

A very easy and straight forward way is to use a polyfill:
First it needs to be installed:
npm i number-to-locale-string-polyfill
This has to be added in your code, best just outside the class/function where you want to use .toLocaleString().
require('number-to-locale-string-polyfill');

I solved this using a custom function
function numberToMoney(amount, simbol = '$', decimalCount = 2, decimal
= ".", thousands = ",") {
decimalCount = Math.abs(decimalCount)
decimalCount = isNaN(decimalCount) ? 2 : decimalCount
const negativeSign = amount < 0 ? "-" : ""
const i = parseInt(amount = Math.abs(Number(amount) ||
0).toFixed(decimalCount)).toString()
const j = (i.length > 3) ? i.length % 3 : 0
return simbol + negativeSign + (j ? i.substr(0, j) + thousands : '') +
i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ?
decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "")
};
No need to install extra packages

Displaying currency values in React Native A zero dependencies solution:
const parseCurr = (value) =>
Platform.OS === 'android'
? '$' + price.toFixed(2)
: price.toLocaleString('en-US', { style: 'currency', currency:'USD' });
parseCurr(25.75) // => $25.75
A real life example (money values are multiplied by 100 for better cents precision) and converting the value to Brazilian Reais (R$)
export const getBRPrice = (price: number) => {
const parsedPrice =
( price / 100 ).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
return Platform.OS === 'android'
? `R$${ ( price / 100 ).toFixed(2) }`
: parsedPrice;
};
// getBRPrice(450) => R$4,50

Solution: 1
Go to your android/app/build.gradle
Replace this line def jscFlavor = 'org.webkit:android-jsc:+'
with this
def jscFlavor = 'org.webkit:android-jsc-intl:+'
Stop the metro and rebuild your app.
Solution: 2
Otherwise, you can use this package https://www.npmjs.com/package/luxon
import import {DateTime} from 'luxon';
const date = DateTime.fromISO(new Date().toISOString());
const formatted = date.toLocaleString(DateTime.DATETIME_MED);
console.log(formatted);

Merging some responses from this thread, you can use this code where it is possible to customize the formatted response
const defaultOptions = {
significantDigits: 2,
thousandsSeparator: ',',
decimalSeparator: '.',
symbol: '$'
}
const currencyFormatter = (value, options) => {
if (typeof value !== 'number') value = 0.0
options = { ...defaultOptions, ...options }
value = value.toFixed(options.significantDigits)
const [currency, decimal] = value.split('.')
return `${options.symbol} ${currency.replace(
/\B(?=(\d{3})+(?!\d))/g,
options.thousandsSeparator
)}${options.decimalSeparator}${decimal}`
}

function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
This will remove commas after decimal point

If you need two digits after the decimal and always want to round down
you can use below code.
Math.floor(1233.31231231 * 100) / 100).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
To round differently check out this resource

If these solutions don't work for you... In my case, I was using React Native with the expo web simulator and wanted to format minutes with 2 characters ie. 00, 01, ... 10, 11, etc. My solution was to check if minutes contained one character, if so, prepend a "0".
... + (date.getMinutes().toString().length == 1 ? "0" : "") + date.getMinutes().toString()

Related

Suitescript 2.0 Adding 3rd party libraries

I have been watching the instructional videos on Youtube from Stoic Software and have tried uploading the following to my Netsuite account to test the creation of third party libraries:
/**
* Prompts the user if the current project has not been re-baselined in some time
*
* #copyright 2020 Stoic Software, LLC
* #author Eric T Grubaugh <eric#stoic.software>
*
* #NApiVersion 2.x
* #NScriptType ClientScript
* #NModuleScope Public
* #NAmdConfig ./amdconfig.json
* #appliedtorecord job
*/
define(["moment"], (moment) => {
const message = "Project has not been re-baselined in over two months.";
function pageInit(context) {
let lastBaseline = moment(
context.currentRecord.getValue({ fieldId: "lastbaselinedate" })
);
if (lastBaseline.isValid() && moment().diff(lastBaseline, "months") >= 2) {
alert(message);
}
}
return { pageInit };
});
This is the amdconfig.json file that sits in the same location as the script:
{
"paths": {
"moment": "./SuiteScripts/sdf_ignore/moment-with-locales.js"
}
}
When I try to create the script record, I get the following error:
Row 14 is the following: define(["moment"], (moment) => {
Can anyone see what the issue is?
Edit: thanks to #fullstack.studio I was able to upload the script.
I am getting the following error message though where it is not recognising the function:
the third party library I am trying to use is the one found under:
https://momentjs.com/
I use path without '.' => /SuiteScripts/.... The '.' is a ref to the current folder. And you may remove the .js ext.
"paths": {
"helper": "/SuiteScripts/My_Helper"
}
In the meta try to use 2.1 instead 2.x
/**
....
* #NApiVersion 2.1
....
*/

How can I override the jetbrains jdk dependency required by idea-ultimate or idea-community in config.nix?

I’ve been setting up my local nix config as per nixpkgs manual's declarative package management.
I’d like to include idea-ultimate as one of myPackages, but at this time the dependency idea has on the jetbrains jdk is broken, pointing to a non-existing package for macOS.
It’s trying to download jbrsdk-11_0_2-osx-x64-b485.1.tar.gz instead of jbrsdk-11_0_4-osx-x64-b485.1.tar.gz.
I was assuming I could fix that by overriding jetbrainsjdk as follows, but I’m getting: error: attribute 'jetbrainsjdk' missing, at /Users/ldeck/.config/nixpkgs/config.nix:4:20 when I do anything like nix-env -qa ‘jetbrains.*’.
What is the right way to override idea-ultimate so that it uses the fixed jdk?
Here’s my ~./config/nixpkgs/config.nix.
{
allowUnfree = true;
packageOverrides = pkgs: rec {
jetbrainsjdk = pkgs.jetbrainsjdk.override {
version = "520.11";
src = pkgs.fetchurl {
url = "https://bintray.com/jetbrains/intellij-jdk/download_file?file_path=jbrsdk-11_0_4-osx-x64-b${jetbrainsjdk.version}.tar.gz";
sha256 = "0d1qwbssc8ih62rlfxxxcn8i65cjgycdfy1dc1b902j46dqjkq9z";
};
};
myProfile = pkgs.writeText "my-profile" ''
export PATH=$HOME/.nix-profile/bin:/nix/var/nix/profiles/default/bin:/sbin:/bin:/usr/sbin:/usr/bin
export MANPATH=$HOME/.nix-profile/share/man:/nix/var/nix/profiles/default/share/man:/usr/share/man
'';
myPackages = with pkgs; buildEnv {
name = "my-packages";
paths = [
(runCommand "profile" {} ''
mkdir -p $out/etc/profile.d
cp ${myProfile} $out/etc/profile.d/my-profile.sh
'')
aspell
bc
coreutils
direnv
emacs
emscripten
ffmpeg
gdb
git
hello
jq
nixops
nox
scala
silver-searcher
];
pathsToLink = [ "/share/man" "/share/doc" "/bin" "/etc" "/Applications" ];
extraOutputsToInstall = [ "man" "doc" ];
};
};
}
UPDATE 1
Thanks to #ChrisStryczynski who suggested I needed with pkgs, I’ve gotten a little further.
But now the problem is when attempting to install idea-ultimate with the custom jdk, it’s still requiring the broken, non-existing, jbrsdk-11_02-osx-x64-b485.1.tar.gz.drv from somewhere.
Updated config and logs below.
{
allowUnfree = true;
packageOverrides = pkgs: **with pkgs;** rec {
myJetbrainsJdk = **pkgs.jetbrains.jdk.overrideAttrs** (oldAttrs: rec {
version = "520.11";
src = pkgs.fetchurl {
url = "https://bintray.com/jetbrains/intellij-jdk/download_file?file_path=jbrsdk-11_0_4-osx-x64-b520.11.tar.gz";
sha256 = "0d1qwbssc8ih62rlfxxxcn8i65cjgycdfy1dc1b902j46dqjkq9z";
};
});
myIdeaUltimate = pkgs.jetbrains.idea-ultimate.override {
jdk = myJetbrainsJdk;
};
...
myPackages = with pkgs; buildEnv {
...
myIdeaUltimate
];
...
};
};
}
Logs
nix-channel --update; nix-env -iA nixpkgs.myPackages
unpacking channels...
replacing old 'my-packages'
installing 'my-packages'
these derivations will be built:
/nix/store/9kfi3k9q6hi7z3lwann318hndbah535v-idea-ultimate.desktop.drv
/nix/store/ica1m5yq3f3y05xnw7ln1lnfvp0yjvyf-download_file?file_path=jbrsdk-11_0_4-osx-x64-b520.11.tar.gz.drv
/nix/store/bf2hwhrvfl8g77gdiw053rayh06x0120-jetbrainsjdk-520.11.drv
/nix/store/fazsa1a4l70s391rjk9yyi2hvrg0zbmp-download_file?file_path=jbrsdk-11_0_2-osx-x64-b485.1.tar.gz.drv
/nix/store/fwwk976sd278zb68zy9wm5pkxss0rnhg-jetbrainsjdk-485.1.drv
/nix/store/s3m2bpcyrnx9dcq4drh95882n0mk1d6m-ideaIU-2019.2.4-no-jbr.tar.gz.drv
/nix/store/9kiajpmmsp3i6ysj4vdqq8dzi84mnr73-idea-ultimate-2019.2.4.drv
/nix/store/jh1ixm54qinv8pk6kypvv6n6cfr4sws8-my-packages.drv
these paths will be fetched (0.02 MiB download, 0.12 MiB unpacked):
/nix/store/hp90sbwznq1msv327f0lb27imvcvi80h-libnotify-0.7.8
building '/nix/store/9kfi3k9q6hi7z3lwann318hndbah535v-idea-ultimate.desktop.drv'...
copying path '/nix/store/hp90sbwznq1msv327f0lb27imvcvi80h-libnotify-0.7.8' from 'https://cache.nixos.org'...
building '/nix/store/fazsa1a4l70s391rjk9yyi2hvrg0zbmp-download_file?file_path=jbrsdk-11_0_2-osx-x64-b485.1.tar.gz.drv'...
trying https://bintray.com/jetbrains/intellij-jdk/download_file?file_path=jbrsdk-11_0_2-osx-x64-b485.1.tar.gz
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
curl: (22) The requested URL returned error: 404 Not Found
error: cannot download download_file?file_path=jbrsdk-11_0_2-osx-x64-b485.1.tar.gz from any mirror
builder for '/nix/store/fazsa1a4l70s391rjk9yyi2hvrg0zbmp-download_file?file_path=jbrsdk-11_0_2-osx-x64-b485.1.tar.gz.drv' failed with exit code 1
building '/nix/store/ica1m5yq3f3y05xnw7ln1lnfvp0yjvyf-download_file?file_path=jbrsdk-11_0_4-osx-x64-b520.11.tar.gz.drv'...
cannot build derivation '/nix/store/fwwk976sd278zb68zy9wm5pkxss0rnhg-jetbrainsjdk-485.1.drv': 1 dependencies couldn't be built
cannot build derivation '/nix/store/9kiajpmmsp3i6ysj4vdqq8dzi84mnr73-idea-ultimate-2019.2.4.drv': 1 dependencies couldn't be built
cannot build derivation '/nix/store/jh1ixm54qinv8pk6kypvv6n6cfr4sws8-my-packages.drv': 1 dependencies couldn't be built
error: build of '/nix/store/jh1ixm54qinv8pk6kypvv6n6cfr4sws8-my-packages.drv' failed
Thanks to How do you discover the override attributes for a derivation, a solution has been found using an overlay.
# ~/config/nixpkgs/overlays/02-jetbrains.nix
self: super:
{
jetbrains = super.jetbrains // {
jdk = super.jetbrains.jdk.overrideAttrs (oldAttrs: rec {
version = "520.11";
src = super.fetchurl {
url = "https://bintray.com/jetbrains/intellij-jbr/download_file?file_path=jbrsdk-11_0_4-osx-x64-b520.11.tar.gz";
sha256 = "3fe1297133440a9056602d78d7987f9215139165bd7747b3303022a6f5e23834";
};
passthru = oldAttrs.passthru // {
home = "${self.jetbrains.jdk}/Contents/Home";
};
});
idea-ultimate = super.jetbrains.idea-ultimate.overrideAttrs (_: {
name = "idea-ultimate.2019.2.4";
src = super.fetchurl {
url = "https://download.jetbrains.com/idea/ideaIU-2019.2.4-no-jbr.tar.gz";
sha256 = "09mz4dx3zbnqw0vh4iqr8sn2s8mvgr7zvn4k7kqivsiv8f79g90a";
};
});
};
}
Install: nix-env -iA 'nixpkgs.jetbrains.idea-ultimate'.
Execute: idea-ultimate.
The crucial part of the puzzle was overriding the passthru.home variable to point to the overlayed JDK rather than the one required by super. Otherwise, you’ll be downloading the old JDK for runtime purposes.
passthru = oldAttrs.passthru // {
home = "${self.jetbrains.jdk}/Contents/Home”;
};
Without /Contents/Home appended, idea won’t startup since self.jetbrains.jdk isn’t a valid home.
Instead of:
nix-env -iA nixpkgs.myPackages
Just do:
nix-env -iA nixpkgs.myIdeaUltimate
The problem being:
myPackages = with pkgs; buildEnv {
...
myIdeaUltimate
];
...
};
Here you are still referencing the old pkgs.myIdeaUltimate.
Nixos seems to do some processing that replaces the pkgs with the appropriate from packageOverrides.

reading ID3 tag in NativeScript + Vue

I am trying to read id3 tags of mp3 files in my project but it seems all the node plugins has a dependency on fs ,
since I get this error: TypeError: fs.exists is not a function
so How can I read id3 tags in NativeScript?
{N} !== Node, You will have to fetch the meta data in native iOS / Android way. Use nativescript-media-metadata-retriever plugin.
tns plugin add nativescript-media-metadata-retriever
You could try nativescript-nodeify, but I remember having problem afterwards with with bundling.
Also, I used this back in NativeScript 4. I don't know if this still works in NS 6.
I share my usage of this module in sake of noobies like me, who can waste their times just for a misunderstanding :))
requires:
import { MediaMetadataRetriever } from "nativescript-media-metadata-retriever";
const imageSourceModule = require( "tns-core-modules/image-source" );
const fs = require("tns-core-modules/file-system");
and the code:
// ------- init MediaMetadataRetriever
let mmr = new MediaMetadataRetriever();
mmr.setDataSource( newValue );
mmr.getEmbeddedPicture()
.then( ( args ) => {
// ------- show the albumArt on bgIMG
var albumArt = this.$refs.bgIMG.nativeView;
var img = new imageSourceModule.ImageSource();
// ------- setNativeSource is a **Methods** of imageSourceModule
img.setNativeSource( args );
albumArt.set( "src" , img );
console.log("ImageSource set...");
// ------- save the albumArt in root of SDCARD
// ------- fromNativeSource is a **Function** of imageSourceModule
let imageSource = imageSourceModule.fromNativeSource( args );
console.log("Here");
let fileName = "test.png";
const root = android.os.Environment.getExternalStorageDirectory().getAbsolutePath().toString();
let path = fs.path.join( root , fileName);
let saved = imageSource.saveToFile(path, "png");
if (saved) {
console.log("Image saved successfully!");
}
} );

Change name of apk depending on buildType

I'd like to change the name of my output .apk files. However, I want to have "-debug" or "-release" appended depending on the build type.
Here are the output names I want:
MyApp-0.0.1-debug.apk
MyApp-0.0.1-release.apk
I'm unfamiliar with Gradle and haven't found how to do this, I know I just need to access the buildType within the following code but can't find how to do this.
Currently my output is "MyApp-0.0.1.apk" regardless of buildType. How can I change the code below to alter this?
android.libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName
def bType = ""
// bType = "-" + something.buildType
fileName = "${archivesBaseName}-${project.version}${bType}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
The build type is part of the variant; you're iterating over all the variants in your loop. You can get the build type name via:
variant.buildType.name
You can find (partially complete) API docs at http://tools.android.com/tech-docs/new-build-system/user-guide
For anyone arriving here late, this version works for me in April 2020.
Just place this code inside your buildTypes element ( android or defaultConfig work just as well).
applicationVariants.all { variant ->
def customBuildName = ""
if(variant.buildType.name == "release") customBuildName = "release-name.apk"
else customBuildName = "build-name.apk"
variant.outputs.all {
outputFileName = customBuildName
println("name of ${variant.buildType.name} build is ${outputFileName}")
}
}

Error in Dojo 1.8 upgrade Error:{"message":"'registry' is undefined"}

I want to set the data in bodydiv how it possible.
Error in Dojo 1.8 upgrade Error:{"message":"'registry' is undefined"}
function setBodyData(link) {
if(!stringExists(link)) {
return;
}
dojo.xhrGet ({
url: link
,timeout: 50000
,content: {session_id:session_logout}
,handleAs:'text'
,load:function(data){
alert("data:"+dumpObj(data));
var l_object = dojo.byId('bodyDiv');
//dijit.byId('bodyDiv').innerHTML = data;
registry.byId('bodyDiv').set('content',data);
}
If understand correctly you now get the error? "'dijit.byId(...)' is null or not an object"?
Make sure the div 'bodyDiv' exists and try:
dom.byId("bodyDiv").innerHTML = data;
Of cause you must also require "dojo/dom".