首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在React本机上使用十进制,以及如何在Listview上对所有行值进行求和

如何在React本机上使用十进制,以及如何在Listview上对所有行值进行求和
EN

Stack Overflow用户
提问于 2017-08-10 07:32:50
回答 3查看 1.4K关注 0票数 0

1.如何在上使用十进制和循环--我需要使用十进制#,###.## (9,000.00) --用于在列表视图上显示

2.如何为千人插入逗号?

3.如何求出和全值(product_price)?

我有这样的api

代码语言:javascript
运行
复制
{
    "success": true,
    "result": [
        {
            "productname": "m1",
            "product_price": "1400.00000", <<<<<<<<<< it's don't have comma

        },
        {
            "productname": "m2",
            "product_price": "60.00000",

        },
        {
            "productname": "m3",
            "product_price": "71400.00000",  <<<<<<<<<< it's don't have comma

        }
    ]
}

渲染

代码语言:javascript
运行
复制
      <ListView
        dataSource={this.state.dataSource}
        renderRow={(rowData) => 
         <Text>{rowData.product_price}</Text>}  <<< I need to set decimal and comma on format = (1,400.00)
      />

<Text> Total =  {this.state.total}</Text> <<<< I need to show total of sum product_price

谢谢

EN

回答 3

Stack Overflow用户

发布于 2017-08-10 07:49:19

您可以使用它来插入数千个逗号,这样您就不需要从api中返回一个逗号分隔的数字。

代码语言:javascript
运行
复制
{((Math.round(rowData.product_price* 100)/100).toLocaleString())}

对于第三个问题,如果您有返回的结果在您的状态。你可以这样做。

代码语言:javascript
运行
复制
    var totalProductPrice = 0

          resultList.forEach(function(result){
            if (result.product_price){
              totalProductPrice += result.product_price
            }
          })
this.setState({total, totalProductPrice});

希望这能有所帮助。

我添加了一个片段来演示您的评论,查看它确实返回了带有逗号的3000。

代码语言:javascript
运行
复制
console.log(((Math.round(3000.000000* 100)/100).toLocaleString()))

票数 1
EN

Stack Overflow用户

发布于 2017-08-10 07:52:05

有很多方法可以格式化数字。简单的方法是安装数字格式的NPM模块

代码语言:javascript
运行
复制
renderRow(rowData) {
  <NumberFormat value={rowData.product_price} displayType={'text'} thousandSeparator={true} prefix={'$'} />
}

对于计算总计,可以循环遍历所有值,并计算状态中的总计和保存。

票数 0
EN

Stack Overflow用户

发布于 2017-08-10 08:05:48

代码语言:javascript
运行
复制
function round(value, decimals) {

   return Number(Math.round(value+'e'+decimals)+'e-'+decimals).toFixed(2);
}
round(1.005, 2); // 1.01

如果使用(Math.round(1.005* 100)/100),则舍入将将数字转换为1而不是1.01

number.toLocaleString()将把数字转换为逗号分隔的局部值。

因此,

代码语言:javascript
运行
复制
renderList() {
  var totalAmount = 0;
  return (
    <View>
      <ListView
         dataSource={this.state.dataSource}
         renderRow={(rowData) => {
             totalAmount += rowData.product_price;
             return (<Text>{this.round(rowData.product_price).toLocaleString()}</Text>);}}
      />
     <Text>Total = {this.round(totalAmount).toLocaleString()}</Text>
  <View>
  );

}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45607245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档