You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
besure_app/src/utils/format.js

40 lines
1.1 KiB
JavaScript

import { getCurrentLocale } from '@/locales'
const ZH_UNITS = [
{ value: 1e8, symbol: '亿' },
{ value: 1e6, symbol: '百万' },
{ value: 1e4, symbol: '万' }
]
const EN_UNITS = [
{ value: 1e9, symbol: 'B' },
{ value: 1e6, symbol: 'M' },
{ value: 1e3, symbol: 'K' }
]
function formatWithUnits(num, units, decimals) {
for (const unit of units) {
if (num >= unit.value) {
const formatted = num / unit.value
const rounded = parseFloat(formatted.toFixed(decimals))
return rounded + unit.symbol
}
}
return num.toLocaleString()
}
export function formatNumber(num, options = {}) {
if (num === null || num === undefined || isNaN(num)) return '-'
const { decimals = 1, locale } = options
const currentLocale = locale || getCurrentLocale()
const isZh = currentLocale.startsWith('zh')
const units = isZh ? ZH_UNITS : EN_UNITS
return formatWithUnits(Number(num), units, decimals)
}
export function formatPercent(num, options = {}) {
if (num === null || num === undefined || isNaN(num)) return '-'
const { decimals = 1 } = options
return parseFloat(Number(num).toFixed(decimals)) + '%'
}