格式化能力

internationalized 基于 Intl.NumberFormat 并扩展了插件机制,适用于多种业务场景。

组件使用

import { NumberFormat } from 'internationalized';

<NumberFormat value={0.1234} style="percent" maximumFractionDigits={2} />;
  • style 支持 decimalcurrencypercent 以及扩展插件样式(如 per-milleper-myriadpercentage-pointcn-upper)。
  • 自动根据本地化规则输出千分位、货币符号和单位。

Hook

import { useFormat } from 'internationalized/hooks';

const { format } = useFormat({ style: 'currency', currency: 'CNY' });
format(123456.789); // => "¥123,456.79"

Hook 在 React 中共享缓存配置,减少重复创建 Intl.NumberFormat 的开销。

函数式 API

import { formatAsDecimal, formatAsCurrency } from 'internationalized/fp';

formatAsDecimal(1234.567, { maximumFractionDigits: 1 });
formatAsCurrency(88.6, 'EUR');

函数式入口便于在非 React 环境或服务端场景使用。

动态小数位控制

通过 extend_dynamicDecimals 扩展选项,可以自动为极小的小数值提升精度,直到出现首个非零小数;若超出阈值,则回退到科学计数法:

import { NumberFormat } from 'internationalized';

<NumberFormat
  value={0.00000031}
  style="decimal"
  extend_dynamicDecimals={{ maxFractionDigits: 8, additionalDigits: 1 }}
/>;
// => "0.00000031"

插件扩展

通过插件可以轻松扩展新的格式化模式:

import { registerNumberFormatPlugin } from 'internationalized/core';

registerNumberFormatPlugin({
  name: 'compact-metric',
  resolve({ value }) {
    if (Math.abs(value) >= 10_000) {
      return { style: 'compact', notation: 'compact' };
    }
    return null;
  }
});

注册后即可在组件、Hook 与函数式 API 中共享。