@cainiaofe/cn-utils
Version:
菜鸟前端基础工具库
68 lines (67 loc) • 2.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.numFormat = exports.numFixed = void 0;
var type_1 = require("../../common/type");
/**
* 保留浮点数位数函数
*
* @param {Number} num
* @param {Number} bit
*/
var numFixed = function (num, bit, round) {
if (bit === void 0) { bit = 2; }
if (round === void 0) { round = true; }
if (!(0, type_1.isNumber)(num)) {
throw new Error('需传递数字类型');
}
// num.toFixed(bit) * 1; //12.145.toFixed(2) 12.14 12.175.toFixed(2) 12.18 银行家舍入规则
if (round) {
// 默认四舍五入
return Math.round(num * Math.pow(10, bit)) / Math.pow(10, bit);
}
else {
// 不四舍五入
num += '';
var index = num.indexOf('.');
if (index === -1) {
return +num;
}
else {
var lastIndex = Math.min(index + bit + 1, num.length);
return +num.slice(0, lastIndex);
}
}
};
exports.numFixed = numFixed;
/**
* 格式化数字
*
* @param {Number} num
* @param {Number} bit
*/
var numFormat = function (num, format) {
if ((0, type_1.isNaN)(num * 1)) {
// 不是数字直接返回
return num;
}
if ((0, type_1.isNumber)(format)) {
// 传递数字,默认保留小数位
return (0, exports.numFixed)(num, format || 2); // 默认保留两位
}
if (format === '%') {
// 传递百分号
return "".concat((0, exports.numFixed)(num * 100, 2), "%");
}
if (format === ',') {
// 传递,默认三数字分隔
return (num &&
(num.toString().indexOf('.') !== -1
? num.toString().replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
return "".concat($1, ",");
})
: num.toString().replace(/(\d)(?=(\d{3})+\b)/g, function ($0, $1) {
return "".concat($1, ",");
})));
}
};
exports.numFormat = numFormat;