Last active
April 14, 2025 09:55
-
-
Save davidmweber/ddd6921138c4ae6156f8d73ee70702f9 to your computer and use it in GitHub Desktop.
Printing engineering units in typescrit
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
const posPrefix = ["", "k", "M", "G", "T", "P"] | |
const negPrefix = ["", "m", "μ", "n", "p", "a"] | |
/** | |
* Convert a number to a metric string in engineering/SI notation. For example, | |
* toMetric(1.2345678e8, "Wh", 4) returns "123.5MWh". | |
* @param value The number to convert to a string. | |
* @param unit A string representing the unit to use e.g. kW, C, V expected | |
* @param The total number of digits to return | |
*/ | |
function toMetric(value: number, unit: string, digits = 4): string { | |
const sign = Math.sign(value) >= 0 ? "": "-" | |
const log = Math.log10(Math.abs(value)) | |
const exp = Math.floor(log) | |
const idx = ~~(exp / 3) // Dang but this is an ugly way to do div. We could use bigints if this becomes a problem | |
const prefix = idx >= 0 ? posPrefix[idx]: negPrefix[-idx] | |
const point = exp > 0 ? digits - exp % 3 - 1 : digits + Math.abs(exp) % 3 - 1 | |
const norm = Math.pow(10, log - exp + exp % 3) | |
const str = norm.toFixed(point) | |
return sign + str + prefix + unit | |
} | |
console.log(toMetric(1.2345e-12, "C")) | |
console.log(toMetric(1.2345e-11, "C")) | |
console.log(toMetric(1.2345e-10, "C")) | |
console.log(toMetric(1.2345e-9, "C")) | |
console.log(toMetric(1.2345e-8, "C")) | |
console.log(toMetric(1.2345e-7, "C")) | |
console.log(toMetric(1.2345e-6, "C")) | |
console.log(toMetric(1.2345e-5, "C")) | |
console.log(toMetric(1.2345e-4, "C")) | |
console.log(toMetric(1.2345e-3, "C")) // 1.234mC | |
console.log(toMetric(1.2345e-2, "C")) // 12.34mC | |
console.log(toMetric(1.2345e-1, "V")) // 0.1234mV | |
console.log(toMetric(1.2345, "Wh")) | |
console.log(toMetric(1.2345e1, "Wh")) | |
console.log(toMetric(1.2345e2, "Wh")) | |
console.log(toMetric(1.2345e3, "Wh")) | |
console.log(toMetric(1.2345e4, "Wh")) | |
console.log(toMetric(1.2345e5, "Wh")) | |
console.log(toMetric(1.2345e6, "Wh")) | |
console.log(toMetric(1.2345e7, "Wh")) | |
console.log(toMetric(1.2345e8, "Wh")) | |
console.log(toMetric(1.2345e9, "Wh")) | |
console.log(toMetric(1.2345e10, "Wh")) | |
console.log(toMetric(1.2345e11, "Wh")) | |
console.log(toMetric(1.2345e12, "Wh")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment