【问题标题】:How to format a number to percentage with two decimals using FormatJs Message Syntax?如何使用 FormatJs 消息语法将数字格式化为两位小数的百分比?
【发布时间】:2018-06-07 19:03:57
【问题描述】:

使用react-intl 我有以下消息:

serviceFee: {
  en: 'Service fee: ({fee, number, percent})',
  ...
},

当我打电话时

<FormatMessage id="serviceFee" values={{ fee: 0.0625 }} />

我希望它呈现:

服务费:6.25%

但我得到一个四舍五入的值:

服务费:6%

如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs react-intl formatjs


    【解决方案1】:

    有两种方法:

    1. 您可以从消息语法中删除百分比样式:

      serviceFee: 'Service fee: ({fee})'
      

      然后以正确的格式发送值:

      <FormatMessage
        id="serviceFee"
        values={{ fee: intl.formatNumber(0.0625, { style: 'percent', maximumFractionDigits: 2 }) }}
      />
      

    或者

    1. 创建设置必要选项的自定义格式:

      const formats = {
        number: {
          percentWith2Decimals: { style: 'percent', maximumFractionDigits: 2 },
        },
      }
      

      将格式添加到您的IntlProvider:

      <IntlProvider formats={formats}>...</IntlProvider>
      

      然后在您的消息中使用自定义格式:

      serviceFee: 'Service fee: ({fee, number, percentWith2Decimals})'
      

    【讨论】:

      【解决方案2】:

      您可以使用来自documentationminimumFractionDigits={2}} 属性。

      import React, { Component } from "react";
      import { FormattedNumber } from "react-intl";
      
      export default class App extends Component {
        render() {
          return (
            <FormattedNumber
              style='percent'
              value={0.0625}
              minimumFractionDigits={2}
            />
          );
        }
      }
      

      以上代码呈现:

      Codesandox.

      【讨论】:

      • 但是我需要使用FormatMessage,因为它里面有文本,我不能加入不同的字符串,因为翻译改变了数字的位置
      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2019-12-28
      • 2020-10-29
      • 2011-06-04
      • 2011-11-01
      相关资源
      最近更新 更多