UNPKG

util-helpers

Version:

一个基于业务场景的工具方法库

69 lines (65 loc) 2.55 kB
'use strict'; var tslib = require('tslib'); var ut2 = require('ut2'); var math_util = require('./utils/math.util.js'); var devWarn = require('./utils/devWarn.js'); var isValidNumber = require('./isValidNumber.js'); function checkNumber(num) { if (!isValidNumber(num)) { devWarn("".concat(num, " invalid parameter.")); return false; } if (typeof num === 'number') { math_util.checkBoundary(num); } return true; } function formatInt(intStr, thousand) { var txt = ''; intStr = math_util.trimLeftZero(intStr); intStr = intStr[0] === '+' ? intStr.substring(1) : intStr; var negativeSymbol = Number(intStr) < 0 ? '-' : ''; var reArr = negativeSymbol ? intStr.substring(1).split('').reverse() : intStr.split('').reverse(); for (var i = 0; i < reArr.length; i++) { txt += reArr[i] + ((i + 1) % 3 === 0 && i + 1 !== reArr.length ? thousand : ''); } return negativeSymbol + txt.split('').reverse().join(''); } function formatDec(decStr, precision, decimal) { if (precision === 0) { return ''; } var zero = 0; var ret = ''; if (decStr && Number(decStr) > 0) { var tmpNum = parseFloat('0.' + decStr); ret = tmpNum.toFixed(precision).substring(2); } else { ret = zero.toFixed(precision).substring(2); } return decimal + ret; } var formatMoney = function (num, options) { if (options === void 0) { options = {}; } var _a = options.precision, precision = _a === void 0 ? 2 : _a, symbol = options.symbol, _b = options.thousand, thousand = _b === void 0 ? ',' : _b, _c = options.decimal, decimal = _c === void 0 ? '.' : _c, _d = options.strict, strict = _d === void 0 ? true : _d; if (!checkNumber(num) || (strict && (!ut2.isString(num) || num === '') && !ut2.isNumber(num))) { return ''; } if (typeof num === 'number' && !isFinite(num)) { return num + ''; } if (typeof precision !== 'number' || ut2.isNaN(precision) || precision < 0) { precision = 2; } else if (precision > 10) { precision = 10; } symbol = typeof symbol === 'string' ? symbol : ''; thousand = typeof thousand === 'string' ? thousand : ','; decimal = typeof decimal === 'string' ? decimal : '.'; var strNum = math_util.transformEffectiveNumber(num) + ''; var _e = tslib.__read(strNum.split('.'), 2), intStr = _e[0], decStr = _e[1]; return symbol + formatInt(intStr, thousand) + formatDec(decStr, precision, decimal); }; module.exports = formatMoney;