vue格式化数字为金额格式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue格式化数字为金额格式

~冰蝶~   2022-06-03 我要评论

格式化数字为金额格式

/**
 * @description 格式化金额
 * @param number:要格式化的数字
 * @param decimals:保留几位小数 默认0位
 * @param decPoint:小数点符号 默认.
 * @param thousandsSep:千分位符号 默认为,
 */
export const formatMoney = (number, decimals = 0, decPoint = '.', thousandsSep = ',') => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  let n = !isFinite(+number) ? 0 : +number
  let prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  let sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
  let dec = (typeof decPoint === 'undefined') ? '.' : decPoint
  let s = ''
  let toFixedFix = function (n, prec) {
    let k = Math.pow(10, prec)
    return '' + Math.ceil(n * k) / k
  }
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  let re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}

格式化金额组件

尤雨溪git下载,这里是引入

const digitsRE = /(\d{3})(?=\d)/g
export function currency(value, currency, decimals) {
  value = parseFloat(value)
  if (!isFinite(value) || (!value && value !== 0)) return ''
  currency = currency != null ? currency : '$'
  decimals = decimals != null ? decimals : 2
  var stringified = Math.abs(value).toFixed(decimals)
  var _int = decimals ?
    stringified.slice(0, -1 - decimals) :
    stringified
  var i = _int.length % 3
  var head = i > 0 ?
    (_int.slice(0, i) + (_int.length > 3 ? ',' : '')) :
    ''
  var _float = decimals ?
    stringified.slice(-1 - decimals) :
    ''
  var sign = value < 0 ? '-' : ''
  return sign + currency + head +
    _int.slice(i).replace(digitsRE, '$1,') +
    _float
}

使用

导入js文件,因为是根据函数名导出,所以,导入需要进行解构

import { currency } from "@/util/currency";
export default {
    .........
    // 局部过滤器
  filters: {
    currency: currency,
  },
 }  

格式化组件使用

 <div class="item-total">
   <span>{{totalPrice | currency('$')}}</span>
</div>

如果在全局使用

main.js
import {
  currency
} from "@/util/currency";
Vue.filter('currency', currency)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们