Run details:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36
Chrome 107
Windows
Desktop
2 years ago
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
HTML Preparation code:
AخA
 
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/9.0.1/bignumber.min.js"></script>
Script Preparation code:
x
 
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}
Tests:
  • toLocaleString

     
    var a = target.toLocaleString('en-US', options);
  • Intl.NumberFormat

     
      var a = new Intl.NumberFormat('en-US', options).format(target)
  • string split & reduce

     
    var a = pricize(target, 3)
  • toFixed

     
    var a = target.toFixed(3)
  • bignumber

     
    var a = new BigNumber(target).toFixed(3)