带逗号和两个小数点的数值格式

loo*_*rge 2 javascript number-formatting chart.js

我正在使用 chart.js 来显示我的销售额问题是我无法将数据正确转换为带有逗号和两位小数的数字格式。

当数据是整数时,输出是正确的。但是,当我显示平均销售额时,我得到的输出是

平均销售额(无格式) 1000.2017
平均销售额(有格式) 1,000.2,017
总销售额(无格式) 1000
总销售额(有格式) 1,000

如何在javascript中正确格式化输出?

tooltips: {
  callbacks: {
     label: function(tooltipItem, data) {
         var value = data.datasets[0].data[tooltipItem.index];
         value = value.toString();
         value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
              return value;
           }
       }
  },
   scales: {
     yAxes: [{
       ticks: {
         userCallback: function(value, index, values) {
           value = value.toString();
           value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
              return value;
         }
        }
    }]
}
Run Code Online (Sandbox Code Playgroud)

azr*_*hel 8

Javascript 为您提供了几个解决方案来做到这一点。下面想到了前两个。

1. number.toLocaleString

As already mentioned, .toLocaleString can help you, but instead of minimumFractionDigits use maximumFractionDigits.

Like below:

number.toLocaleString(undefined, { maximumFractionDigits: 2 })
Run Code Online (Sandbox Code Playgroud)

So summarizing:

const decimalsFormated = number.toLocaleString(undefined, { maximumFractionDigits: 2 })
Run Code Online (Sandbox Code Playgroud)

And than

const finalFormated = String(decimalsFormated).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Run Code Online (Sandbox Code Playgroud)

2. Number.parseFloat + toFixed

let number = 123.1234
Number.parseFloat(number).toFixed(2);
Run Code Online (Sandbox Code Playgroud)

In each approach, wrap your solution in function preferably:

function getCommaSeparatedTwoDecimalsNumber(number) {
    const fixedNumber = Number.parseFloat(number).toFixed(2);
    return String(fixedNumber).replace(/\B(?=(\d{3})+(?!\d))/g, ",");

}
Run Code Online (Sandbox Code Playgroud)

You could also use regex. I would say it is overaly complicated though.

Also very important thing to notice is that you may or may not want to round your final outcome.

Using toLocaleString with maxDigits will just remove everything after those two digits. Using toFixed will round your output unproperly.

This solution will round it properly:

Number(Math.round(1.005+'e2')+'e-2').toFixed(2);
Run Code Online (Sandbox Code Playgroud)

Pasted from here: Format number to always show 2 decimal places

Last thing, probably most important. Depending on what format input number will have, above solution may or may not work. You need to decide on input format and if that cant be foreseen, provide formaters for each possibility:

1000000.123124

10000123123

100000,1239

1.12039

1,19012

etc.

And depending on format, order of actions you need to take may vary.