小编典典

在React中,如何用逗号格式化数字?

reactjs

我的API正在发送React整数,例如10, 31312, 4000

在我的React组件中,格式化这些数字的正确方法是:

from: 10, 31312, 4000
to: 10, 31,312, 4,000

更新资料

该数字由我的Rails API提供并在React组件中呈现:

const RankingsList = ({rankings, currentUserId}) => {
  return (
      <div className="listGroup">
        {rankings.map((ranking, index) =>
            <span className="number">{ranking.points}</span>
        )}
      </div>
  );
};

阅读 1380

收藏
2020-07-22

共1个答案

小编典典

在JavaScript中以逗号分隔的数字作为千位分隔符

您可以为此找到一个通用的JS解决方案:


toLocaleString:

// A more complex example: 
number.toLocaleString(); // "1,234,567,890"

// A more complex example: 
var number2 = 1234.56789; // floating point example
number2.toLocaleString(undefined, {maximumFractionDigits:2}) // "1,234.57"

NumberFormat (不支持Safari):

var nf = new Intl.NumberFormat();
nf.format(number); // "1,234,567,890"

var number = 1234567890; //要转换的示例编号

⚠记住javascript的最大整数值为9007199254740991


其他解决方案:

https://css-tricks.com/snippets/javascript/comma-values-in-
numbers/

2345643.00将返回2,345,643.00

2020-07-22