* Round the parsed number to the specified number of decimal places * This function changed the parsedNumber in-place
(parsedNumber, fractionSize, minFrac, maxFrac)
| 22667 | * This function changed the parsedNumber in-place |
| 22668 | */ |
| 22669 | function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { |
| 22670 | var digits = parsedNumber.d; |
| 22671 | var fractionLen = digits.length - parsedNumber.i; |
| 22672 | |
| 22673 | // determine fractionSize if it is not specified; `+fractionSize` converts it to a number |
| 22674 | fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; |
| 22675 | |
| 22676 | // The index of the digit to where rounding is to occur |
| 22677 | var roundAt = fractionSize + parsedNumber.i; |
| 22678 | var digit = digits[roundAt]; |
| 22679 | |
| 22680 | if (roundAt > 0) { |
| 22681 | // Drop fractional digits beyond `roundAt` |
| 22682 | digits.splice(Math.max(parsedNumber.i, roundAt)); |
| 22683 | |
| 22684 | // Set non-fractional digits beyond `roundAt` to 0 |
| 22685 | for (var j = roundAt; j < digits.length; j++) { |
| 22686 | digits[j] = 0; |
| 22687 | } |
| 22688 | } else { |
| 22689 | // We rounded to zero so reset the parsedNumber |
| 22690 | fractionLen = Math.max(0, fractionLen); |
| 22691 | parsedNumber.i = 1; |
| 22692 | digits.length = Math.max(1, roundAt = fractionSize + 1); |
| 22693 | digits[0] = 0; |
| 22694 | for (var i = 1; i < roundAt; i++) digits[i] = 0; |
| 22695 | } |
| 22696 | |
| 22697 | if (digit >= 5) { |
| 22698 | if (roundAt - 1 < 0) { |
| 22699 | for (var k = 0; k > roundAt; k--) { |
| 22700 | digits.unshift(0); |
| 22701 | parsedNumber.i++; |
| 22702 | } |
| 22703 | digits.unshift(1); |
| 22704 | parsedNumber.i++; |
| 22705 | } else { |
| 22706 | digits[roundAt - 1]++; |
| 22707 | } |
| 22708 | } |
| 22709 | |
| 22710 | // Pad out with zeros to get the required fraction length |
| 22711 | for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); |
| 22712 | |
| 22713 | |
| 22714 | // Do any carrying, e.g. a digit was rounded up to 10 |
| 22715 | var carry = digits.reduceRight(function(carry, d, i, digits) { |
| 22716 | d = d + carry; |
| 22717 | digits[i] = d % 10; |
| 22718 | return Math.floor(d / 10); |
| 22719 | }, 0); |
| 22720 | if (carry) { |
| 22721 | digits.unshift(carry); |
| 22722 | parsedNumber.i++; |
| 22723 | } |
| 22724 | } |
| 22725 | |
| 22726 | /** |
no test coverage detected