* Round the parsed number to the specified number of decimal places * This function changed the parsedNumber in-place
(parsedNumber, fractionSize, minFrac, maxFrac)
| 20830 | * This function changed the parsedNumber in-place |
| 20831 | */ |
| 20832 | function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { |
| 20833 | var digits = parsedNumber.d; |
| 20834 | var fractionLen = digits.length - parsedNumber.i; |
| 20835 | |
| 20836 | // determine fractionSize if it is not specified; `+fractionSize` converts it to a number |
| 20837 | fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; |
| 20838 | |
| 20839 | // The index of the digit to where rounding is to occur |
| 20840 | var roundAt = fractionSize + parsedNumber.i; |
| 20841 | var digit = digits[roundAt]; |
| 20842 | |
| 20843 | if (roundAt > 0) { |
| 20844 | // Drop fractional digits beyond `roundAt` |
| 20845 | digits.splice(Math.max(parsedNumber.i, roundAt)); |
| 20846 | |
| 20847 | // Set non-fractional digits beyond `roundAt` to 0 |
| 20848 | for (var j = roundAt; j < digits.length; j++) { |
| 20849 | digits[j] = 0; |
| 20850 | } |
| 20851 | } else { |
| 20852 | // We rounded to zero so reset the parsedNumber |
| 20853 | fractionLen = Math.max(0, fractionLen); |
| 20854 | parsedNumber.i = 1; |
| 20855 | digits.length = Math.max(1, roundAt = fractionSize + 1); |
| 20856 | digits[0] = 0; |
| 20857 | for (var i = 1; i < roundAt; i++) digits[i] = 0; |
| 20858 | } |
| 20859 | |
| 20860 | if (digit >= 5) { |
| 20861 | if (roundAt - 1 < 0) { |
| 20862 | for (var k = 0; k > roundAt; k--) { |
| 20863 | digits.unshift(0); |
| 20864 | parsedNumber.i++; |
| 20865 | } |
| 20866 | digits.unshift(1); |
| 20867 | parsedNumber.i++; |
| 20868 | } else { |
| 20869 | digits[roundAt - 1]++; |
| 20870 | } |
| 20871 | } |
| 20872 | |
| 20873 | // Pad out with zeros to get the required fraction length |
| 20874 | for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); |
| 20875 | |
| 20876 | |
| 20877 | // Do any carrying, e.g. a digit was rounded up to 10 |
| 20878 | var carry = digits.reduceRight(function(carry, d, i, digits) { |
| 20879 | d = d + carry; |
| 20880 | digits[i] = d % 10; |
| 20881 | return Math.floor(d / 10); |
| 20882 | }, 0); |
| 20883 | if (carry) { |
| 20884 | digits.unshift(carry); |
| 20885 | parsedNumber.i++; |
| 20886 | } |
| 20887 | } |
| 20888 | |
| 20889 | /** |
no test coverage detected