Test name | Executions per second |
---|---|
toLocaleString | 45039.9 Ops/sec |
Intl.NumberFormat | 43292.6 Ops/sec |
string split & reduce | 1393152.2 Ops/sec |
toFixed | 3243237.8 Ops/sec |
bignumber | 768151.4 Ops/sec |
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/9.0.1/bignumber.min.js"></script>
function pricize (num, decimal = 0) {
const intPart = Math.floor(num)
const intPieces = intPart.toString().split('')
const len = intPieces.length
const intStr = intPieces.reduce((result, chr, index, array) => {
const pos = len - index
result += (index !== 0 && pos % 3 === 0) ? ',' + chr : chr
return result
}, '')
const decStr = decimal > 0
? num.toFixed(decimal + 1).toString().slice(-(decimal + 2), -1) // toFixed() は四捨五入してしまうので(decimal + 1)桁まで求めて切り取る
: ''
return intStr + decStr
}
var target = 123456789.123456789
var options = {minimumFractionDigits: 3, maximumFractionDigits: 3}
var a = target.toLocaleString('en-US', options);
var a = new Intl.NumberFormat('en-US', options).format(target)
var a = pricize(target, 3)
var a = target.toFixed(3)
var a = new BigNumber(target).toFixed(3)