Skip to content

Instantly share code, notes, and snippets.

@JakeTheCorn
Created January 16, 2020 20:28
Show Gist options
  • Save JakeTheCorn/a87943abf9596c104a01918bac3fa40e to your computer and use it in GitHub Desktop.
Save JakeTheCorn/a87943abf9596c104a01918bac3fa40e to your computer and use it in GitHub Desktop.
Utility that returns decimal strings to a certain precision.
function toPrecisionString(num: number, precision: number): string {
if (typeof num !== 'number' || typeof precision !== 'number') {
throw new TypeError('toPrecisionString(n: number, precision: number): string => was called with non-number arguments')
}
if (isInt(num)) {
let extension = ''
if (precision === 0) {
return String(num)
} else {
extension += '.'
for (let i = 0; i < precision; i++) {
extension += '0'
}
}
return String(num) + extension
} else {
if (precision === 0) {
return String(parseInt(num as any))
}
const str = String(num)
let [base, extension] = str.split('.')
if (extension.length > precision) {
extension = extension.substring(0, precision)
} else {
for (let i = 0; i < precision - extension.length + 1; i++) {
extension += '0'
}
}
return base + '.' + extension
}
}
function isInt(subject: unknown): boolean {
if (typeof subject !== 'number') {
return false
}
const str = String(subject)
return /^[0-9]+$/.test(str)
}
const tables = [
table([3.3333, 3], '3.333'),
table([3, 3], '3.000'),
table([3, 0], '3'),
table([3.55, 4], '3.5500'),
table([3.5, 0], '3', 'can be lossy'),
]
describe('toPrecisionString(num: number, precision: number): string', () => {
tables.forEach(t => {
it(t.message || `returns ${JSON.stringify(t.expectation)} when given ${JSON.stringify(t.input)}`, () => {
const result = toPrecisionString(t.input[0], t.input[1])
expect(result).toEqual(t.expectation)
})
})
})
function table(input, expectation, message?) { return { input, expectation, message } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment