number.toLocaleString() is not working in react-native

Viewed 3165

number.toLocaleString() is not working in react-native, can anyone suggest better way to format currency in react-native, code goes here

formatMoney(number) {

        if(number===undefined||number===null)
        {
            return 0
        }
        else
        {
            var n=number.toString
            var obj={
                style:'currency',
                currency:'GBP'
            }
            'use strict'
           return n.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' });
        }
      }
2 Answers

You want to use the Number.toLocaleString function, therefore you need to make sure that you are calling it on a number and not on a string. See example below:

var n = 5555;
//var n=number.toString(); remove this line
var obj={
    style:'currency',
    currency:'GBP'
}

formatted = n.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' });
console.log("formatted",formatted);

You can use this library react-number-format. It has these features

  1. Prefix, suffix and thousand separator.
  2. Custom format pattern.
  3. Masking.
  4. Custom formatting handler.
  5. Format number in an input or format as a simple text

Sample usage

<NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />

Output : $2,456,981

Related