Skip to content

Instantly share code, notes, and snippets.

@gokhantaskan
Last active March 17, 2023 20:12
Show Gist options
  • Save gokhantaskan/7caffd0b475d19e51d589728d1d6e4fe to your computer and use it in GitHub Desktop.
Save gokhantaskan/7caffd0b475d19e51d589728d1d6e4fe to your computer and use it in GitHub Desktop.
CO₂ mass unit conversion
// ! Co2 always in tons
export function convertCO2Units(co2t: number): string {
const units = ["g", "kg", "t"];
let co2g = co2t * 1_000_000; // convert to grams
let unitIndex = 0;
while (co2g > 1000 && unitIndex < units.length - 1) {
co2g /= 1000;
unitIndex++;
}
return `${co2g.toFixed(2)} ${units[unitIndex]}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment