UNPKG

util-helpers

Version:

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

67 lines (64 loc) 2.56 kB
import { __read } from 'tslib'; import { isString, isNumber, isNaN } from 'ut2'; import { transformEffectiveNumber, checkBoundary, trimLeftZero } from './utils/math.util.js'; import devWarn from './utils/devWarn.js'; import isValidNumber from './isValidNumber.js'; function checkNumber(num) { if (!isValidNumber(num)) { devWarn("".concat(num, " invalid parameter.")); return false; } if (typeof num === 'number') { checkBoundary(num); } return true; } function formatInt(intStr, thousand) { var txt = ''; intStr = 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 && (!isString(num) || num === '') && !isNumber(num))) { return ''; } if (typeof num === 'number' && !isFinite(num)) { return num + ''; } if (typeof precision !== 'number' || 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 = transformEffectiveNumber(num) + ''; var _e = __read(strNum.split('.'), 2), intStr = _e[0], decStr = _e[1]; return symbol + formatInt(intStr, thousand) + formatDec(decStr, precision, decimal); }; export { formatMoney as default };