使用React原生Expo时,如何将数字格式化为货币?

shstlldc  于 2022-12-24  发布在  React
关注(0)|答案(9)|浏览(243)

如何将10000这样的数字输出为$10,000.00?我甚至遇到了String.format(...)的问题,错误为Not a function
我看了很多文章,都不完整,也没有一个能用。我不需要完全的国际化,只需要格式化数字的能力

v7pvogib

v7pvogib1#

您可以使用toFixed方法显示2个小数点。

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

你可以像这样使用正则表达式

function currencyFormat(num) {
   return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
console.log(currencyFormat(2665)); // $2,665.00
qoefvg9y

qoefvg9y2#

您可以使用react-number-format库。它具有以下特性
1.前缀、后缀和千位分隔符。
1.自定义格式模式。
1.伪装。
1.自定义格式处理程序。
1.设置输入中数字的格式或设置为简单文本的格式
样品使用

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

产出:2 456 981美元

4si2a6ki

4si2a6ki3#

编辑:对不起-这是一个ReactIdeJS解决方案-不是ReactNative。上面的都不适合我...但是这个家伙有正确的想法/解决方案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
baubqpgj

baubqpgj4#

若要避免使用库,可以使用以下代码

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}`
}
jslywgbw

jslywgbw5#

最快的方法是使用react-number-format,如上所述,但是不要忘记renderText属性,这样React Native就不会抛出渲染错误。
请执行以下步骤:
1.安装。使用以下命令:

npm i react-number-format

1.在React Native应用中使用它,如下所示:

import React from 'react';
import NumberFormat from 'react-number-format';

export function ReactNativeNumberFormat({ value }) {
  return (
    <NumberFormat
      value={value}
      displayType={'text'}
      thousandSeparator={true}
      prefix={'$'}
      renderText={formattedValue => <Text>{formattedValue}</Text>} // <--- Don't forget this!
    />
  );
}

正如你所看到的,我最终创建了我的自定义组件,它接受value作为 prop ,这样我就可以在任何需要的地方使用它。

<View>
    <ReactNativeNumberFormat value={530000} />
  </View>

希望是有用的。
PS:这是我的参考=〉https://github.com/s-yadav/react-number-format/issues/17#issuecomment-395187806.

gz5pxeao

gz5pxeao6#

使用toLocaleString本机React函数:

const formatNumber = (q) => {
    return q.toLocaleString('en-US', {
        style: 'currency',
        currency: 'USD'
    })
   }
vuv7lop3

vuv7lop37#

我最近写了下面的数字格式实用程序,它可以在OP的情况下使用,也可以在其他情况下使用。希望修改它以覆盖其他情况是相当简单的(我希望大多数人都想改变我的默认值)。

type NumberFormatProps = {
  value: number;
  thousandSeparator?: string;
  decimalSeparator?: string;
  significantDigits?: number;
  showTrailingZeros?: boolean;
  symbol?: '$' | 'kr.' | '%'; // Add other symbols as needed
  showSymbol?: boolean;
  symbolPosition?: 'before' | 'after';
  showSymbolSpace?: boolean;
};

/**
 * Formats a number. Supports changing symbol, thousand and decimal separators and more (see props).
 * @param value The value to format
 * @param thousandSeparator The separator to use between thousands
 * @param decimalSeparator The separator to use before decimals
 * @param significantDigits The number of significant digits to show
 * @param showTrailingZeros Whether to show trailing zeros for significant digits (i.e. 1,00 if significant digits is 2)
 * @param symbol The  symbol to use
 * @param showSymbol Whether to show the symbol
 * @param symbolPosition Whether to show the symbol before or after the value
 * @param showSymbolSpace Whether to show a space between the  symbol and the value
 * @returns
 */
export const getFormattedNumber = ({
  value,
  thousandSeparator = '.',
  decimalSeparator = ',',
  significantDigits = 0,
  showTrailingZeros = false,
  symbol = 'kr.',
  showSymbol = true,
  symbolPosition = 'after',
  showSymbolSpace = true,
}: NumberFormatProps) => {
  const significantDigitsExponent = 10 ** significantDigits;
  const valueWithSignificantDigits = showTrailingZeros
    ? // If significant digits is 2 then this is e.g. 1.00, 1.10, 1.11
      value.toFixed(significantDigits)
    : // If significant digits is 2 then this is e.g. 1, 1.1, 1.11
      `${Math.round((value + Number.EPSILON) * significantDigitsExponent) / significantDigitsExponent}`;

  // Split the value into the parts before and after the decimal point
  const [integerPart, fractionalPart] = valueWithSignificantDigits.toString().split('.');
  // Replace thousand separator in integer part
  const formattedIntegerPart = `${integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator)}`;
  // Add decimal separator and fractional part if needed
  const formattedValue = fractionalPart
    ? `${formattedIntegerPart}${decimalSeparator}${fractionalPart}`
    : formattedIntegerPart;

  // Add symbol
  if (showSymbol && Boolean(symbol)) {
    const formattedValueWithSymbol =
      symbolPosition === 'after' ? `${formattedValue} ${symbol}` : `${symbol} ${formattedValue}`;
    return showSymbolSpace ? formattedValueWithSymbol : formattedValueWithSymbol.replace(' ', '');
  }

  return formattedValue;
};

在OP的情况下,这将被称为:

getFormattedNumber({
  value: 10000,
  thousandSeparator: ',',
  decimalSeparator: '.',
  symbol: "$",
  showSymbolSpace: false,
  symbolPosition: 'before',
  significantDigits: 2,
  showTrailingZeros: true
})
7d7tgy0s

7d7tgy0s8#

export const CurrencyFormatter = (number, options) => {
  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);

    let valueFormatted;

    if (options.significantDigits == 0) {
      const [currency] = value.split(".");
      valueFormatted = `${options.symbol}${currency.replace(
        /\B(?=(\d{3})+(?!\d))/g,
        newOptions.thousandsSeparator
      )}`;
    } else {
      const [currency, decimal] = value.split(".");
      valueFormatted = `${options.symbol}${currency.replace(
        /\B(?=(\d{3})+(?!\d))/g,
        options.thousandsSeparator
      )}${options.decimalSeparator}${decimal}`;
    }

    return valueFormatted;
  };

  return currencyFormatter(number, options);
};
aelbi1ox

aelbi1ox9#

可以如下所示实现,如果没有小数,还可以删除末尾的尾随00

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

相关问题