Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you format a number to currency when using React native Expo?

How do I take a number like 10000 and have it output as $10,000.00? I even had a problem with String.format(...) with a Not a function error.

I followed numerous articles, all incomplete and none working. I don't need full internationalization, just the ability to format a number

like image 602
Choco Avatar asked Apr 07 '19 06:04

Choco


People also ask

How to format currency in React Native?

To format a number to currency when using React Native, we can use the react-number-format package. To install it, we run npm i react-number-format . to add the NumberFormat component. value is set to the number to format.

How do you put commas in numbers in react?

To format a number with commas in React, we can use the number's toLocaleString method. We call toLocaleString on 1234.56789 with { maximumFractionDigits: 2 } to return a number string that has the comma digit separators and the rounded to 2 decimal places. Therefore, we see 1,234.57 displayed.

How do I format a new date in React Native?

To format a date string in React Native, we can use moment. js. to call moment with a JavaScript date object to create a moment object with the same date. Then we call format with a format string to return a date string with the given date.


2 Answers

You can use toFixed method for showing 2 decimal point.

let num = 1000;  console.log(num.toFixed(2)); // 1000.00 

And you can use Regex like this

function currencyFormat(num) {    return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') } console.log(currencyFormat(2665)); // $2,665.00
like image 80
Robin Avatar answered Sep 27 '22 16:09

Robin


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

like image 23
Masuk Helal Anik Avatar answered Sep 27 '22 16:09

Masuk Helal Anik