0

我正在尝试通过格式化程序格式化表格中的数字,以一种方式,以逗号分隔千位,用点分隔小数。

我设置了以下格式化程序函数,它可以处理非数字值和可能的失败空值:

  this.table.formatter = (val, col) => {

    const numberWithCommas = (x, decimals) => {
      var parts = x.toString().split(".");
      parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      if(parts[1]){
        parts[1] = Number(parts[1]).toFixed(decimals);
      } 
      return decimals > 0 ? parts.join(".") : parts[0];
    }

    let res;
    if (col == "period" || col == "channel") {
      res = isNaN(val) ? val : " ";
      return res;
    } else {
      const decimals = this.config.data.metric["format"]["decimals"] | 0;

      if (val != null) {
        if (!isNaN(val)) {
          res = numberWithCommas(val, decimals);
        } else {
          res = val;
        }

        return res != " " ? this.config.data.metric["format"].prefix + " " + res + " " + this.config.data.metric["format"].postfix : "";
      }else{
        return "";
      }
    }

  }

对于没有小数的数字(变量“小数”为 0 的数字),它可以完美地工作并用逗号分隔数字。但是对于小数,结果是可怕的,完全没有意义:

在此处输入图像描述

编辑:

这是两行的示例原始数据包,因此您可以看到原始数据的样子。在这些情况下,它们是带有大量小数的浮点数:

在此处输入图像描述

你知道这里出了什么问题吗?谢谢!

4

2 回答 2

1

波纹管代码对我有用

var N = 1000;

console.log(N.toLocaleString());

您可以参考numObj.toLocaleString

于 2018-07-12T09:49:38.403 回答
0

收到的所有评论/答案的混合,以及对文档的一点阅读,让我找到了方法:

res = val.toLocaleString("en-IN", {maximumFractionDigits: decimals, minimumFractionDigits: decimals}); 

单独使用“.toLocaleString()”方法不会将千位分隔符作为逗号,因为我在西班牙。但是设置“en-IN”语言环境,开始将它们作为分隔符。然后,使用文档中的选项,我可以轻松设置固定数量的小数。

现在效果很好。谢谢大家!

于 2018-07-12T09:57:24.697 回答