UNPKG

@numio/bigmath

Version:

@numio/bigmath is an arbitrary-precision arithmetic library. It can be used for basic operations with decimal numbers (integers and float)

45 lines (44 loc) 1.86 kB
import { HALF_UP } from "./constants.js"; import { calcLast, handleCarryOver, handleTail } from "./utils.js"; /** This function round number. */ export const round = (value, options) => { var _a, _b, _c, _d; const roundMode = (_a = options === null || options === void 0 ? void 0 : options.roundMode) !== null && _a !== void 0 ? _a : HALF_UP; let array = []; let sigFig = (_b = options === null || options === void 0 ? void 0 : options.sigFig) !== null && _b !== void 0 ? _b : false; let decimals = (_c = options === null || options === void 0 ? void 0 : options.decimals) !== null && _c !== void 0 ? _c : 0; let isFloat = false; let isNil = true; for (let i = 0; i < value.length; i++) { const charCode = value.charCodeAt(i); if (sigFig && charCode > 48) sigFig = false; if (isNil && charCode > 48) isNil = false; if (isFloat && !sigFig) decimals -= 1; if (charCode === 46) isFloat = true; if (isFloat && decimals === 0) { const next = (_d = value.charCodeAt(i + 1)) !== null && _d !== void 0 ? _d : 0; const prev = value.charCodeAt(i - 1); const curr = charCode === 46 ? prev : charCode; const [last, hasCarryOver] = calcLast(curr, next, roundMode); if (charCode === 46) isFloat = false; if (hasCarryOver) { [array, isFloat] = handleCarryOver(array, isFloat); break; } charCode === 46 ? array[array.length - 1] += last - prev : array.push(last); break; } array.push(charCode); } handleTail(array, isFloat); return (isNil && array[array.length - 1] <= 48) ? "0" : String.fromCharCode(...array); };