vue3 国际化-数值格式化
1 货币格式化
export function formatTwoEuro(value, decimals = 2, currency = 'EUR', locale = 'es-ES') {
if (!value) {
return getZeroValue(decimals, locale);
}
const numValue = Number(value);
if (!Number.isFinite(numValue)) {
return getZeroValue(decimals, locale);
}
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency,
minimumFractionDigits: decimals,
maximumFractionDigits: decimals
}).format(numValue);
};
function getZeroValue(decimals, locale) {
const formatter = new Intl.NumberFormat(locale);
const decimalSeparator = formatter.format(1.1).replace(/1/g, '').charAt(0);
return `0${decimalSeparator}${'0'.repeat(decimals)}`;
}
2 百分比 格式化
export function formatPercent(value, minDecimals = 1, maxDecimals = 2, locale = 'es-ES') {
if (!value) {
return getZeroValue(minDecimals, locale);
}
const numValue = Number(value);
if (!Number.isFinite(numValue)) {
return getZeroValue(minDecimals, locale);
}
return new Intl.NumberFormat(locale, {
style: 'percent',
minimumFractionDigits: minDecimals,
maximumFractionDigits: maxDecimals
}).format(numValue / 100);
}
function getZeroValue(decimals, locale) {
const formatter = new Intl.NumberFormat(locale);
const decimalSeparator = formatter.format(1.1).replace(/1/g, '').charAt(0);
return `0${decimalSeparator}${'0'.repeat(decimals)}`;
}
3 全局注册
import { formatTwoEuro, formatPercent } from '@/utils/okyun'
app.config.globalProperties.formatTwoEuro = formatTwoEuro
app.config.globalProperties.formatPercent = formatPercent
4 项目中使用
<template>
......
<el-descriptions-item label="现金找零: ">
<span :style="{ color: shiftForm.totalChange < 0 ? '#ff4949' : 'inherit' }">
{{ formatTwoEuro(shiftForm.totalChange) }}
</span>
</el-descriptions-item>
......
</template>
<script>
......
// 计算合计行
const getSummaries = (param) => {
const { columns, data } = param;
const sums = [];
columns.forEach((column, index) => {
if (index === 0) {
sums[index] = '合计';
return;
}
if (column.property === 'detailQuantity') {
// 计算数量合计
sums[index] = data.reduce((sum, row) => sum + (Number(row.detailQuantity) || 0), 0) ;
} else if (column.property === 'detailSalesAmount') {
// 计算金额合计
const total = data.reduce((sum, row) => sum + (Number(row.detailSalesAmount) || 0), 0) ;
sums[index] = proxy.formatTwoEuro(total);
} else {
// 其他列不合计
sums[index] = '';
}
});
return sums;
};
......
</script>