Created
December 5, 2017 01:39
-
-
Save zzzzBov/5282aee37e2b1df65620bec0e1c3523a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
toFixed = (value, fractionDigits) => { | |
const f = | |
fractionDigits === undefined | |
? 0 | |
: +fractionDigits | |
console.log('1. f:', f) | |
if (f < 0 || f > 20) { | |
console.error('2. throw a RangeError') | |
throw new RangeError('fractionDigits must be between 0 and 20') | |
} | |
let x = +value | |
console.log('3. x:', x) | |
if (isNaN(x)) { | |
console.log('4. x is NaN') | |
return 'NaN' | |
} | |
let s = '' | |
console.log('5. s:', s) | |
if (x < 0) { | |
s = '-' | |
x = -x | |
console.log('6. s:', s, 'x:', x) | |
} | |
let m | |
if (x >= 10e21) { | |
m = x.toString() | |
console.log(`7. m:`, m) | |
} else { | |
console.group('8.') | |
const n0 = x * 10 ** f | |
const n1 = Math.floor(n0) | |
const n2 = Math.ceil(n0) | |
const v1 = Math.abs(n1 / 10 ** f - x) | |
const v2 = Math.abs(n2 / 10 ** f - x) | |
console.log('8.a. n0:', n0) | |
console.log('n1:', n1, 'v1:', v1) | |
console.log('n2:', n2, 'v2:', v2) | |
let n | |
if (v1 < v2) { | |
n = n1 | |
} else if (v2 < v1) { | |
n = n2 | |
} else if (n1 < n2) { | |
n = n2 | |
} else { | |
n = n1 | |
} | |
console.log('n:', n) | |
if (n === 0) { | |
m = '0' | |
} else { | |
m = n.toString() | |
} | |
if (f != 0) { | |
let k = m.length | |
if (k <= f) { | |
let z = '0'.repeat(f + 1 - k) | |
m = z + m | |
k = f + 1 | |
} | |
let a = m.slice(0, k - f) | |
let b = m.slice(k - f) | |
m = a + '.' + b | |
} | |
console.groupEnd() | |
} | |
return s + m | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment