1. Number to thousands place
/*
* 默认返回当前数字千分位格式
* 参数说明:
* number:要格式化的数字
* decimals:保留几位小数
* dec_point:小数点符号
* thousands_sep:千分位符号
* roundtag:舍入参数,默认 "ceil" 向上取,"floor"向下取,"round" 四舍五入
* 默认为保留两位小数,以逗号隔开,四舍五入
* */
export function formatCurrency(
number: string | number,
decimals = 2,
dec_point = '.',
thousands_sep = ',',
roundtag = 'round'
) {
if (isEmpty(number)) {
return null
} else {
number = (number + '').replace(/[^0-9+-Ee.]/g, '')
roundtag = roundtag || 'ceil' // "ceil","floor","round"
const n = !isFinite(+number) ? 0 : Number(number) // 检查number是否是无穷大
const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
const dec = typeof dec_point === 'undefined' ? '.' : dec_point
let s: any = ''
const toFixedFix = function(n: number, prec: number) {
const k = Math.pow(10, prec) // 10 的 prec 次幂
return (
'' +
parseFloat(
Math[roundtag](parseFloat((n * k).toFixed(prec * 2))).toFixed(
prec * 2
)
) /
k
) // 解析一个字符串,并返回一个浮点数。
}
s = (prec ? toFixedFix(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 toNonExponential(s.join(dec))
}
}
2. Convert scientific notation to decimal
/**
* 将科学计数法转换为小数
* @param num
* @returns
*/
export function toNonExponential(num: any) {
if (num.indexOf('E') !== -1 || num.indexOf('e') !== -1) {
// 验证是否为科学计数法
const m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/)
return num.toFixed(Math.max(0, (m[1] || '').length - m[2]))
} else {
return num
}
}
3. Remove the thousandth place
/**
* 去除千分位
*@param{Object}num
*/
export function delcommafy(num: any) {
if (num === null) {
return null
}
if ((num + '').trim() === '') {
return ''
}
num = String(num).replace(/,/gi, '')
return num
}