* Round the parsed number to the specified number of decimal places * This function changed the parsedNumber in-place
(parsedNumber, fractionSize, minFrac, maxFrac)
| 22602 | * This function changed the parsedNumber in-place |
| 22603 | */ |
| 22604 | function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { |
| 22605 | var digits = parsedNumber.d; |
| 22606 | var fractionLen = digits.length - parsedNumber.i; |
| 22607 | |
| 22608 | // determine fractionSize if it is not specified; `+fractionSize` converts it to a number |
| 22609 | fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; |
| 22610 | |
| 22611 | // The index of the digit to where rounding is to occur |
| 22612 | var roundAt = fractionSize + parsedNumber.i; |
| 22613 | var digit = digits[roundAt]; |
| 22614 | |
| 22615 | if (roundAt > 0) { |
| 22616 | // Drop fractional digits beyond `roundAt` |
| 22617 | digits.splice(Math.max(parsedNumber.i, roundAt)); |
| 22618 | |
| 22619 | // Set non-fractional digits beyond `roundAt` to 0 |
| 22620 | for (var j = roundAt; j < digits.length; j++) { |
| 22621 | digits[j] = 0; |
| 22622 | } |
| 22623 | } else { |
| 22624 | // We rounded to zero so reset the parsedNumber |
| 22625 | fractionLen = Math.max(0, fractionLen); |
| 22626 | parsedNumber.i = 1; |
| 22627 | digits.length = Math.max(1, roundAt = fractionSize + 1); |
| 22628 | digits[0] = 0; |
| 22629 | for (var i = 1; i < roundAt; i++) digits[i] = 0; |
| 22630 | } |
| 22631 | |
| 22632 | if (digit >= 5) { |
| 22633 | if (roundAt - 1 < 0) { |
| 22634 | for (var k = 0; k > roundAt; k--) { |
| 22635 | digits.unshift(0); |
| 22636 | parsedNumber.i++; |
| 22637 | } |
| 22638 | digits.unshift(1); |
| 22639 | parsedNumber.i++; |
| 22640 | } else { |
| 22641 | digits[roundAt - 1]++; |
| 22642 | } |
| 22643 | } |
| 22644 | |
| 22645 | // Pad out with zeros to get the required fraction length |
| 22646 | for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); |
| 22647 | |
| 22648 | |
| 22649 | // Do any carrying, e.g. a digit was rounded up to 10 |
| 22650 | var carry = digits.reduceRight(function(carry, d, i, digits) { |
| 22651 | d = d + carry; |
| 22652 | digits[i] = d % 10; |
| 22653 | return Math.floor(d / 10); |
| 22654 | }, 0); |
| 22655 | if (carry) { |
| 22656 | digits.unshift(carry); |
| 22657 | parsedNumber.i++; |
| 22658 | } |
| 22659 | } |
| 22660 | |
| 22661 | /** |
no test coverage detected