* Round the parsed number to the specified number of decimal places * This function changed the parsedNumber in-place
(parsedNumber, fractionSize, minFrac, maxFrac)
| 19609 | * This function changed the parsedNumber in-place |
| 19610 | */ |
| 19611 | function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { |
| 19612 | var digits = parsedNumber.d; |
| 19613 | var fractionLen = digits.length - parsedNumber.i; |
| 19614 | |
| 19615 | // determine fractionSize if it is not specified; `+fractionSize` converts it to a number |
| 19616 | fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; |
| 19617 | |
| 19618 | // The index of the digit to where rounding is to occur |
| 19619 | var roundAt = fractionSize + parsedNumber.i; |
| 19620 | var digit = digits[roundAt]; |
| 19621 | |
| 19622 | if (roundAt > 0) { |
| 19623 | digits.splice(roundAt); |
| 19624 | } else { |
| 19625 | // We rounded to zero so reset the parsedNumber |
| 19626 | parsedNumber.i = 1; |
| 19627 | digits.length = roundAt = fractionSize + 1; |
| 19628 | for (var i=0; i < roundAt; i++) digits[i] = 0; |
| 19629 | } |
| 19630 | |
| 19631 | if (digit >= 5) digits[roundAt - 1]++; |
| 19632 | |
| 19633 | // Pad out with zeros to get the required fraction length |
| 19634 | for (; fractionLen < fractionSize; fractionLen++) digits.push(0); |
| 19635 | |
| 19636 | |
| 19637 | // Do any carrying, e.g. a digit was rounded up to 10 |
| 19638 | var carry = digits.reduceRight(function(carry, d, i, digits) { |
| 19639 | d = d + carry; |
| 19640 | digits[i] = d % 10; |
| 19641 | return Math.floor(d / 10); |
| 19642 | }, 0); |
| 19643 | if (carry) { |
| 19644 | digits.unshift(carry); |
| 19645 | parsedNumber.i++; |
| 19646 | } |
| 19647 | } |
| 19648 | |
| 19649 | /** |
| 19650 | * Format a number into a string |
no test coverage detected