how do you format a number to currency when using React native EXPO?

拟墨画扇 提交于 2020-04-10 07:07:46

问题


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


回答1:


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




回答2:


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



回答3:


None of the above worked for me ... but this chap had the right idea / solution https://medium.com/@nidhinkumar/react-js-number-format-and-styling-a1a6e211e629

const numberFormat = (value) =>
  new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR'
  }).format(value);

numberFormat(50000); //output as ₹ 50,000.00
numberFormat(10000); //output as ₹ 10,000.00



回答4:


could be achieved as shown below, and you could also remove trailing 00 at the end if there is no decimals

      costing= () => {
        const cost= 1478.90 + 940;
        return parseFloat(cost).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
      }


来源:https://stackoverflow.com/questions/55556221/how-do-you-format-a-number-to-currency-when-using-react-native-expo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!