首页 > 解决方案 > 如何使用 react i18next 库格式化货币

问题描述

我有一个 create-react-app,我需要为其添加 i18n 支持。我打算使用https://github.com/i18next但在文档中我找不到如何格式化货币。

有人如何使用 react i18next 库格式化货币吗?

非常感谢你的帮助

标签: reactjsi18next

解决方案


您可以使用Intl.NumberFormat以格式化货币。

为了将它与i18next我使用的格式选项集成。

i18next.init({
  lng: 'en',
  debug: false,
  resources: {
    en: {
      translation: {
        "key": "{{value, price, EUR}}"
      }
    }
  },
  interpolation: {
    format: (value, rawFormat, lng) => {
      const [format, ...additionalValues] = rawFormat.split(',').map((v) => v.trim());
      switch (format) {
        case 'uppercase':
          return value.toUpperCase();
        case 'price':
          return Intl.NumberFormat(lng, {
            style: 'currency',
            currency: additionalValues[0]
          }).format(value);
      }
    }
  }
}).then(function(t) {
  // initialized and ready to go!
  document.getElementById('output').innerHTML = t('key', {
    value: 1000.01
  });
});
<script src="https://unpkg.com/i18next/dist/umd/i18next.min.js"></script>

<div id="output"></div>


推荐阅读