analytics/assets/js/dashboard/number-formatter.js
Uku Taht c4c0bb2095 Various formatting improvements
* Format numbers over 1B
* Show full number when hovering
2021-03-24 12:08:05 +02:00

52 lines
1.5 KiB
JavaScript

const THOUSAND = 1000
const HUNDRED_THOUSAND = 100000
const MILLION = 1000000
const HUNDRED_MILLION = 100000000
const BILLION = 1000000000
const HUNDRED_BILLION = 100000000000
const TRILLION = 1000000000000
export default function numberFormatter(num) {
if (num >= THOUSAND && num < MILLION) {
const thousands = num / THOUSAND
if (thousands === Math.floor(thousands) || num >= HUNDRED_THOUSAND) {
return Math.floor(thousands) + 'k'
} else {
return (Math.floor(thousands * 10) / 10) + 'k'
}
} else if (num >= MILLION && num < BILLION) {
const millions = num / MILLION
if (millions === Math.floor(millions) || num >= HUNDRED_MILLION) {
return Math.floor(millions) + 'M'
} else {
return (Math.floor(millions * 10) / 10) + 'M'
}
} else if (num >= BILLION && num < TRILLION) {
const billions = num / BILLION
if (billions === Math.floor(billions) || num >= HUNDRED_BILLION) {
return Math.floor(billions) + 'B'
} else {
return (Math.floor(billions * 10) / 10) + 'B'
}
} else {
return num
}
}
function pad(num, size) {
return ('000' + num).slice(size * -1);
}
export function durationFormatter(duration) {
const hours = Math.floor(duration / 60 / 60)
const minutes = Math.floor(duration / 60) % 60
const seconds = Math.floor(duration - (minutes * 60) - (hours * 60 * 60))
if (hours > 0) {
return `${hours}h ${minutes}m ${seconds}s`
} else if (minutes > 0) {
return `${minutes}m ${pad(seconds, 2)}s`
} else {
return `${seconds}s`
}
}