Display comma separated Number using locale string

2019-06-06 05:19发布

I need to display the numbers with comma separated like 120,456.02

I tried the below method using js and it worked fine. But in apps scripts, it throws illegal radix exception

function toDec(n) {
    //return parseFloat(Math.round(n * 100) / 100).toFixed(2) + ' '; will display without comma
    return Number(parseFloat(Math.round(n * 100) / 100)).toLocaleString('en-US', {minimumFractionDigits: 2});
}

Any workaround available?

1条回答
神经病院院长
2楼-- · 2019-06-06 05:26

In GAS toLocaleString is just an alias for toString, and is therefore useless. (Relevant bug tracker item from Rhino, on which GAS runs.)

So, we have to do some manual comma insertion following Add commas or spaces to group every three digits:

var n = 123456.789;
var str = n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');

where str is now 123,456.79.

查看更多
登录 后发表回答