vue常见数值处理封装
参考:https://juejin.cn/post/6844903951876227080
js:
//保留n位小数并格式化输出(不足的部分补0)
var fomatFloat = function(value, n) {
var f = Math.round(value*Math.pow(10,n))/Math.pow(10,n)
var s = f.toString();
var rs = s.indexOf('.')
if (rs < 0) {
s += '.'
}
for(var i = s.length - s.indexOf('.'); i <= n; i++){
s += "0"
}
return s
}
TS:
/**
*
* @param value 处理值
* @param fixed 精确到小数点后位数,不足补0
* @returns
*/
export function NumberSplitByComma(value: string | number, fixed = 0): string {
if (value === undefined || value === '') {
return '0';
}
let ret = '';
const str = value.toString();
if (str.indexOf('.') !== -1) {
let [a, b] = str.split('.');
a = a.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
if (b.length > fixed) {
b = b.slice(0, fixed);
} else {
b = b.padEnd(fixed, '0');
}
ret = `${a}.${b}`;
} else {
ret = str.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
if (fixed) {
ret = `${ret}.`;
ret = ret.padEnd(ret.length + fixed, '0');
}
}
return ret;
}
/**
*
* @param value 处理值
* @param fixed 四舍五入到小数点后位数,不足补0,
* @returns
*/
export function formatNumber(value: string | number, fixed = 2): string {
if (!value) {
return `0.${''.padEnd(fixed, '0')} `;
}
let budget = (+value).toFixed(fixed);
budget = NumberSplitByComma(budget, fixed);
return budget;
}