2023-05-15 08:51:32 +08:00
|
|
|
/*
|
2023-08-14 12:46:28 +08:00
|
|
|
* Formats a number with comma separators.
|
2023-05-15 08:51:32 +08:00
|
|
|
formatNumber(1234567) will return '1,234,567'
|
|
|
|
formatNumber(1234567.89) will return '1,234,567.89'
|
|
|
|
*/
|
|
|
|
export const formatNumber = (num: number | string) => {
|
2023-08-14 12:46:28 +08:00
|
|
|
if (!num)
|
|
|
|
return num
|
|
|
|
const parts = num.toString().split('.')
|
|
|
|
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
|
|
|
return parts.join('.')
|
2023-05-15 08:51:32 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
export const formatFileSize = (num: number) => {
|
2023-08-14 12:46:28 +08:00
|
|
|
if (!num)
|
|
|
|
return num
|
|
|
|
const units = ['', 'K', 'M', 'G', 'T', 'P']
|
|
|
|
let index = 0
|
2023-05-15 08:51:32 +08:00
|
|
|
while (num >= 1024 && index < units.length) {
|
2023-08-14 12:46:28 +08:00
|
|
|
num = num / 1024
|
|
|
|
index++
|
2023-05-15 08:51:32 +08:00
|
|
|
}
|
2023-08-14 12:46:28 +08:00
|
|
|
return `${num.toFixed(2)}${units[index]}B`
|
2023-05-15 08:51:32 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
export const formatTime = (num: number) => {
|
2023-08-14 12:46:28 +08:00
|
|
|
if (!num)
|
|
|
|
return num
|
|
|
|
const units = ['sec', 'min', 'h']
|
|
|
|
let index = 0
|
2023-05-15 08:51:32 +08:00
|
|
|
while (num >= 60 && index < units.length) {
|
2023-08-14 12:46:28 +08:00
|
|
|
num = num / 60
|
|
|
|
index++
|
2023-05-15 08:51:32 +08:00
|
|
|
}
|
2023-08-14 12:46:28 +08:00
|
|
|
return `${num.toFixed(2)} ${units[index]}`
|
2023-05-15 08:51:32 +08:00
|
|
|
}
|
2025-02-17 17:05:13 +08:00
|
|
|
|
|
|
|
export const downloadFile = ({ data, fileName }: { data: Blob; fileName: string }) => {
|
|
|
|
const url = window.URL.createObjectURL(data)
|
|
|
|
const a = document.createElement('a')
|
|
|
|
a.href = url
|
|
|
|
a.download = fileName
|
|
|
|
document.body.appendChild(a)
|
|
|
|
a.click()
|
|
|
|
a.remove()
|
|
|
|
window.URL.revokeObjectURL(url)
|
|
|
|
}
|