国际化 - 项目实战3 - vue3 数值格式国际化

132 阅读1分钟

vue3 国际化-数值格式化

1 货币格式化

// currency币种、locale格式 为了根据国际化动态控制货币类型
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);
  }
  // 使用 Intl.NumberFormat 进行欧盟格式格式化'es-ES'
  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);
  }
  // 使用 Intl.NumberFormat 进行欧盟格式格式化
  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>