使用 React 原生博览会时,如何将数字格式化为货币



如何获取像10000这样的数字并将其输出为$10,000.00?我什至遇到了Not a function错误String.format(...)的问题。

我关注了许多文章,所有文章都不完整,没有一篇有效。我不需要完全国际化,只需要格式化数字

您可以使用此库 react-number-format 。 它具有这些功能

  1. 前缀、后缀和千位分隔符。
  2. 自定义格式模式。
  3. 掩蔽。
  4. 自定义格式处理程序。
  5. 设置输入中的数字格式或格式为简单文本

示例用法

<NumericFormat value={2456981.toFixed(2)} displayType={'text'} thousandSeparator={true} prefix={'$'} />

产出 : $2,456,981.00

编辑:抱歉 - 这是一个 React.js解决方案 - 不是 React Native。以上都对我不起作用...但是这个小伙子有正确的想法/解决方案 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

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

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

最快的方法是使用 react-number-format 如上所述,但不要忘记 renderText prop,以便 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作为道具的自定义组件,因此我可以在需要它的任何地方使用它。就像这样:

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

希望是有用的。

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

使用 toLocaleString 本机 React 函数:

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

版本

  • 打字稿:4.7.2
  • 反应:18.2.0

组件:货币.tsx

import React from "react";
interface IProps {
  price: number;
}
const Currency: React.FC<IProps> = ({ price }) => {
  return (
    <>
    {Intl.NumberFormat('en-US', {
      style: 'currency', 
      currency: 'USD' // Change this
      }).format(price)}
    </>
  );
}
export default Currency;

在页面组件中

<Currency price={10000} />

结果

$ 10 000,00

对于印度货币的使用,要了解更多信息,请点击链接 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

 const number= 123.45679;
const currencyFormatter = Intl.NumberFormat("en-IN", {
  style: "currency",
  currency: "INR",
  maximumFractionDigits: 3,
});
currencyFormatter .format(number);

其他人使用,如 Intl.NumberFormat 对象

 console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// Expected output: "123.456,79 €"

日元不使用次要单位

console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));

预计产量:"123,457日元">

我最近编写了以下数字格式实用程序,可用于 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
})
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);
};

你:)好吗!您还可以选择创建 javscript 函数,并使用该函数显示要使用以下格式显示的"数字"值($10,000.00(:

function currencyFormat(num) {
    const numericValue = Number(num); // Convert the value to number
         if (isNaN(numericValue)) {
             // If not a valid number, return an empty string or the original value
             return "";
         } else {
             return "$" + numericValue.toFixed(2).replace(/(d)(?=(d{3})+(?!d))/g, "$1,"); // And this would be the function
         }
     }

您也可以在您需要的每个.js.tsx文件中添加它,或者不添加整个函数,您可以在带有"createContext(("的上下文类型的根路径中创建一个文件,您可以在此处指导自己更多"使用"createContext(("的指南,这样您只需从该上下文文件中获取函数,并且在.js.tsx文件中呈现的代码更少。我希望我已经帮助:)<</p>

div class="one_answers">可以实现如下所示

,如果没有小数,您也可以删除末尾的尾随 00

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

最新更新