vue js格式化數字為金額格式代碼
更新時間:2022年04月21日 10:25:04 作者:~冰蝶~
這篇文章主要介紹了vue js格式化數字為金額格式代碼,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
格式化數字為金額格式
/**
* @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)以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
解決使用vue-awesome-swiper組件手動滾動點擊失效問題
這篇文章主要介紹了使用vue-awesome-swiper組件手動滾動點擊失效問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06
vue進入頁面時不在頂部,檢測滾動返回頂部按鈕問題及解決方法
這篇文章主要介紹了vue進入頁面時不在頂部,檢測滾動返回頂部按鈕問題及解決方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10

