0

I have a value from 0 to 1. I would like to format it with three significant digits as a percent. So for value = 1 it will be 100%, for 0.9563 it will be 95.6% and for 0.02641 it will be 2.64%.

I found that in JavaScript this works fine:

new Intl.NumberFormat('en-us', { 
  style: 'percent', 
  minimumSignificantDigits: 3 }).format(value);

For NativeScript I realize that this object is not supported directly but I have to install special plug-in: nativescript-intl

So, I did it by the command: tns plugin add nativescript-intl.

After I added the code to view-model file:

const intl = require("nativescript-intl");

const percentConverter = {
    toView(value) {
        return new intl.NumberFormat('en-IN',{ 
            style: 'percent', 
            maximumSignificantDigits: 3
        }).format(value);
    },
}

...
    const viewModel = observableModule.fromObject({
        /* Add your view model properties here */
        percentConverter: percentConverter,
...

Also, I changed the XML file:

<Label text="{{ value, value | percentConverter() }}"/>

Now the value displayed as percent but absolutely without fraction digits. So for value = 0.9643 it shows 96%, for value = 0.0025 it shows 0%.

How to configure NativeScript to shows three significant digits?

Manoj
  • 21,753
  • 3
  • 20
  • 41
Jegors Čemisovs
  • 608
  • 6
  • 14
  • I don't see `minimumSignificantDigits` / `maximumSignificantDigits` parameters actually used at all in the plugin source code, you might want to raise a bug on the plugin repo. Setting `{minimumFractionDigits: 1, maximumFractionDigits: 3}` could be a workaround. – Manoj Nov 25 '19 at 18:44
  • Thanks, Manoj. I raised the issue at the repo, I think it is the bug in the plugin – Jegors Čemisovs Nov 25 '19 at 20:45

0 Answers0