js解决数字运算丢失精度,保留小数位
/** * 左补齐字符串 * @param {Number} nLen 要补齐的长度 * @param {String} ch 要补齐的字符 * @return {String} 补齐后的字符串 */ var padLeft = function (str, nLen, ch) { var len = 0, s = str ? str : ""; // 默认要补齐0 ch = ch ? ch : '0'; len = s.length; while (len < nLen) { s = ch + s; len++; } return s; }
/** * 右补齐字符串 * @param {Number} nLen 要补齐的长度 * @param {String} ch 要补齐的字符 * @return {String} 补齐后的字符串 */ var padRight = function (str, nLen, ch) { var len = 0, s = str ? str : ""; // 默认要补齐0 ch = ch ? ch : '0'; len = s.length; while (len < nLen) { s = s + ch; len++; } return s; }
/** * 左移小数点的位置(用于数学计算,相当于除以Math.pow(10, scale) * @param {Number} str 要移动的字符串 * @param {Number} scale 要移位的刻度 * @return {String} 返回移位后的数字字符串 */ var movePointLeft = function (str, scale) { var s, s1, s2, ch, ps, sign; ch = '.'; sign = ''; s = str ? str : ""; if (scale <= 0) return s; ps = s.split('.'); s1 = ps[0] ? ps[0] : ""; s2 = ps[1] ? ps[1] : ""; if (s1.slice(0, 1) == "-") { // 负数 s1 = s1.slice(1); sign = '-'; } if (s1.length <= scale) { ch = "0."; s1 = this.padLeft(s1, scale); } return sign + s1.slice(0, -scale) + ch + s1.slice(-scale) + s2; }
/** * 右移小数点位置(用于数学计算,相当于乘以Math.pow(10, scale) * @param {Number} str 要移动的字符串 * @param {Number} scale 要移位的刻度 * @return {String} 返回移位后的数字字符串 */ var movePointRight = function (str, scale) { var s, s1, s2, ch, ps; ch = '.'; s = str ? str : ""; if (scale <= 0) return s; ps = s.split('.'); s1 = ps[0] ? ps[0] : ""; s2 = ps[1] ? ps[1] : ""; if (s2.length <= scale) { ch = ''; s2 = this.padRight(s2, scale, ch); } return s1 + s2.slice(0, scale) + ch + s2.slice(scale, s2.length); }
/** * 移动小数点位置(用于数学计算,相当于(乘以/除以)Math.pow(10, scale) * @param {Number} str 要移动的字符串 * @param {Number} scale 要移位的刻度(正数表示向右移动;负数表示向左移动;0返回原值) * @return {String} 返回移位后的数字字符串 */ var movePoint = function (str, scale) { if (scale >= 0) { return this.movePointRight(str, scale); } else { return this.movePointLeft(str, -scale); } }
// 提高数字的易读性,在数字每隔3位处增加逗号 var prettyNumeric = function (num, separator) { if (isNaN(num)) return num.toString(); var s = num.toString().split('.'), isNegative = num < 0 ? true : false, s1 = isNegative ? s[0].replace('-', '') : s[0], s2 = s[1] || '', l = s1.length, r = ''; separator = !separator ? ',' : separator; if (l > 3) { var l1 = parseInt(l / 3), idx = l % 3; r = idx == 0 ? '' : s1.slice(0, idx) + separator; for (var i = 0; i < l1; i++) { r += s1.slice(idx + (i * 3), (idx + (i + 1) * 3)) + separator; } r = (isNegative ? '-' : '') + r.slice(0, -1) + (s2.length > 0 ? ('.' + s2) : ''); } else { r = num; } return r; };