Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active December 7, 2017 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/0d84b88a965c5fae7719d941e7b99e2e to your computer and use it in GitHub Desktop.
Save dfkaye/0d84b88a965c5fae7719d941e7b99e2e to your computer and use it in GitHub Desktop.
more fun with number formatting; kind of polyfill for Intl.NumberFormat()
// 3 Nov 2017
// more fun with number formatting; kind of polyfill for `Intl.NumberFormat()`
var format = function(value) {
// 3-digit decimal is default for `Intl.NumberFormat()`
// unless specified in minimumFractionDigits, maximumFractionDigits options
// which is not supported here (yet).
var s = value.toString()
// NOTE 4 Dec 2017 -- Number.toFixed() bug - digits ending in 5, fixing by one decimal place.
// see https://dfkaye.wordpress.com/2017/12/06/number-tofixed-rounding-errors-broken-but-fixable/
value = Number(s.indexOf('.') > -1 ? s.concat('1') : value).toFixed(3)
if (value != Number(value)) {
return '' + value
}
// `parseFloat` removes insignificant decimal zeroes
var parts = parseFloat(value).toString().split('.')
var integer = parts[0].split('')
var fraction = parts[1] || ''
// insertion loop
var formatted = integer.reduce(function(v, d, i, arr) {
var comma = (i < arr.length - 1) && ((arr.length - (1 + i)) % 3 == 0) ? ',' : ''
return v + d + comma
}, '');
return formatted + (fraction && ('.' + fraction))
}
console.log('\n' )
console.info('/* test it out */')
console.log('comma-in-value returns NaN: ', format('1,468.9')) // NaN
console.log('should format from string: ', format('1468.9')) // 1,468.9
console.log('should format from number: ', format(14568.9)) // 14,568.9
console.log('should format the integer, not the fraction: ', format('14568.999')) // 14,568.999
console.log('should round up the fraction to 3 places: ', format('14568.1125')) // BUG: 14,568.112; FIXED: 14,568.113
console.log('should drop insignificant fraction digits: ', format('14568.299999')) // 14,568.3
console.log('integer: ', format('1555')) // 1,555
console.log('\n' )
console.info('/* compare with built-in Intl.NumberFormat() */')
var f = new Intl.NumberFormat()
console.log('comma-in-value returns NaN: ', f.format('1,468.9')) // NaN
console.log('should format from string: ', f.format('1468.9')) // 1,468.9
console.log('should format from number: ', f.format(14568.9)) // 14,568.9
console.log('should format the integer, not the fraction: ', f.format('14568.999')) // 14,568.999
// 4 DEC 2017 - Intl.NumberFormat#format rounds up as expected.
console.log('should round up the fraction to 3 places: ', f.format('14568.1125')) // !! CORRECT !! 14,568.113
console.log('should drop insignificant fraction digits: ', f.format('14568.299999')) // 14568.3
console.log('integer', f.format('1555')) // 1,555
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment