* Round the parsed number to the specified number of decimal places * This function changed the parsedNumber in-place
(parsedNumber, fractionSize, minFrac, maxFrac)
| 21770 | * This function changed the parsedNumber in-place |
| 21771 | */ |
| 21772 | function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { |
| 21773 | var digits = parsedNumber.d; |
| 21774 | var fractionLen = digits.length - parsedNumber.i; |
| 21775 | |
| 21776 | // determine fractionSize if it is not specified; `+fractionSize` converts it to a number |
| 21777 | fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; |
| 21778 | |
| 21779 | // The index of the digit to where rounding is to occur |
| 21780 | var roundAt = fractionSize + parsedNumber.i; |
| 21781 | var digit = digits[roundAt]; |
| 21782 | |
| 21783 | if (roundAt > 0) { |
| 21784 | // Drop fractional digits beyond `roundAt` |
| 21785 | digits.splice(Math.max(parsedNumber.i, roundAt)); |
| 21786 | |
| 21787 | // Set non-fractional digits beyond `roundAt` to 0 |
| 21788 | for (var j = roundAt; j < digits.length; j++) { |
| 21789 | digits[j] = 0; |
| 21790 | } |
| 21791 | } else { |
| 21792 | // We rounded to zero so reset the parsedNumber |
| 21793 | fractionLen = Math.max(0, fractionLen); |
| 21794 | parsedNumber.i = 1; |
| 21795 | digits.length = Math.max(1, roundAt = fractionSize + 1); |
| 21796 | digits[0] = 0; |
| 21797 | for (var i = 1; i < roundAt; i++) digits[i] = 0; |
| 21798 | } |
| 21799 | |
| 21800 | if (digit >= 5) { |
| 21801 | if (roundAt - 1 < 0) { |
| 21802 | for (var k = 0; k > roundAt; k--) { |
| 21803 | digits.unshift(0); |
| 21804 | parsedNumber.i++; |
| 21805 | } |
| 21806 | digits.unshift(1); |
| 21807 | parsedNumber.i++; |
| 21808 | } else { |
| 21809 | digits[roundAt - 1]++; |
| 21810 | } |
| 21811 | } |
| 21812 | |
| 21813 | // Pad out with zeros to get the required fraction length |
| 21814 | for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); |
| 21815 | |
| 21816 | |
| 21817 | // Do any carrying, e.g. a digit was rounded up to 10 |
| 21818 | var carry = digits.reduceRight(function(carry, d, i, digits) { |
| 21819 | d = d + carry; |
| 21820 | digits[i] = d % 10; |
| 21821 | return Math.floor(d / 10); |
| 21822 | }, 0); |
| 21823 | if (carry) { |
| 21824 | digits.unshift(carry); |
| 21825 | parsedNumber.i++; |
| 21826 | } |
| 21827 | } |
| 21828 | |
| 21829 | /** |
no test coverage detected