javascript jsx React 组件中的格式编号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29320562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format number in jsx React component
提问by Eric Baldwin
I am writing a jsx file and want to format the display of numbers in a table. Here is the code for the table:
我正在编写一个 jsx 文件并希望格式化表格中数字的显示。这是表的代码:
<tr>
<td>
{stringVar}
</td>
<td>
{numberVar}
</td>
</tr>
The numberVar is being printed directly; how can I display that number with C-style string formatting (I need to set precision value, add commas, and a $ character)?
numberVar 正在直接打印;如何使用 C 样式字符串格式显示该数字(我需要设置精度值、添加逗号和 $ 字符)?
回答by Daniel Earwicker
You can use any JS expression to format the value. A popular number formatting library is http://numeraljs.com/but there are many others of course.
您可以使用任何 JS 表达式来格式化该值。一个流行的数字格式库是http://numeraljs.com/,当然还有很多其他的。
As for prefixing it with $, that's just string concatenation:
至于用 $ 作为前缀,那只是字符串连接:
{"$" + numberVar}
Or, using string interpolationES6 syntax :
或者,使用字符串插值ES6 语法:
{`$ ${numberVar}`}