Created
August 9, 2022 10:47
-
-
Save 44100hertz/a4685b122c3a1c1d077e1d98b8ef8435 to your computer and use it in GitHub Desktop.
Number shortener
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
function shortNumber (num, desiredDigits) { | |
if (num < 0) { | |
// Negative | |
return '-' + shortNumber(-num, desiredDigits-1); | |
} else if (num === 0) { | |
// Zero is problematic | |
return '0'; | |
} | |
function standardNotation (num, desiredDigits) { | |
const digitsAboveZero = Math.ceil(Math.log10(num)); | |
if (num !== Math.floor(num)) --desiredDigits; // has decimal point | |
// Round off unwanted digits | |
const divisor = Math.pow(10, desiredDigits - digitsAboveZero); | |
const roundNum = Math.floor(num * divisor + 0.5) / divisor; | |
if (num < 1.0) { | |
// Cut off 0 for 0.x | |
return roundNum.toString().slice(1); | |
} else { | |
return roundNum.toString(); | |
} | |
} | |
function scientificNotation (num, desiredDigits) { | |
const exponent = Math.floor(Math.log10(num)); | |
const estr = 'e' + exponent; // exponent string | |
const divisor = Math.pow(10, exponent); | |
const mantissa = standardNotation(Math.floor(num / divisor), desiredDigits - estr.length); | |
return mantissa + estr; // Concat! | |
} | |
function fallbackNotation (num) { | |
return num < 1 ? '0' : '∞'; | |
} | |
const standard = standardNotation(num, desiredDigits); | |
if (standard.length <= desiredDigits) return standard; | |
const scientific = scientificNotation(num, desiredDigits); | |
if (scientific.length <= desiredDigits) return scientific; | |
return fallbackNotation(num); | |
} | |
const testCases = [ | |
[0, 5, '0'], | |
[500, 5, '500'], | |
[1/3.0, 5, '.3333'], | |
[1/3.0, 2, '.3'], | |
[-1/3.0, 5, '-.333'], | |
[-1/3.0, 3, '-.3'], | |
[55.555, 3, '56'], | |
[55.555, 4, '55.6'], | |
[55.555, 5, '55.56'], | |
[5000, 3, '5e3'], | |
[500, 2, '∞'], | |
[-500, 2, '-∞'], | |
[0.05, 3, '.05'], | |
[0.0005, 3, '0'], | |
[-0.0005, 3, '-0'], | |
[0.0005, 4, '5e-4'], | |
[-0.0005, 5, '-5e-4'], | |
]; | |
testCases.forEach((([num, desiredDigits, expected]) => { | |
const result = shortNumber(num, desiredDigits); | |
if (result !== expected) { | |
console.log(result, expected); | |
} | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment