UNPKG

press-ui

Version:

简单、易用的跨端组件库,兼容 Vue2 和 Vue3,同时支持 uni-app和普通 Vue 项目

31 lines (27 loc) 1.07 kB
import { round } from './digit'; /** * @description 数字格式化 * @param {number|string} number 要格式化的数字 * @param {number} decimals 保留几位小数 * @param {string} decimalPoint 小数点符号 * @param {string} thousandsSeparator 千分位符号 * @returns {string} 格式化后的数字 */ export function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparator = ',') { number = (`${number}`).replace(/[^0-9+-Ee.]/g, ''); const n = !isFinite(+number) ? 0 : +number; const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals); const sep = (typeof thousandsSeparator === 'undefined') ? ',' : thousandsSeparator; const dec = (typeof decimalPoint === 'undefined') ? '.' : decimalPoint; let s = ''; s = (prec ? `${round(n, prec)}` : `${Math.round(n)}`).split('.'); const 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); }