* Round the parsed number to the specified number of decimal places * This function changed the parsedNumber in-place
(parsedNumber, fractionSize, minFrac, maxFrac)
| 21881 | * This function changed the parsedNumber in-place |
| 21882 | */ |
| 21883 | function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { |
| 21884 | var digits = parsedNumber.d; |
| 21885 | var fractionLen = digits.length - parsedNumber.i; |
| 21886 | |
| 21887 | // determine fractionSize if it is not specified; `+fractionSize` converts it to a number |
| 21888 | fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; |
| 21889 | |
| 21890 | // The index of the digit to where rounding is to occur |
| 21891 | var roundAt = fractionSize + parsedNumber.i; |
| 21892 | var digit = digits[roundAt]; |
| 21893 | |
| 21894 | if (roundAt > 0) { |
| 21895 | // Drop fractional digits beyond `roundAt` |
| 21896 | digits.splice(Math.max(parsedNumber.i, roundAt)); |
| 21897 | |
| 21898 | // Set non-fractional digits beyond `roundAt` to 0 |
| 21899 | for (var j = roundAt; j < digits.length; j++) { |
| 21900 | digits[j] = 0; |
| 21901 | } |
| 21902 | } else { |
| 21903 | // We rounded to zero so reset the parsedNumber |
| 21904 | fractionLen = Math.max(0, fractionLen); |
| 21905 | parsedNumber.i = 1; |
| 21906 | digits.length = Math.max(1, roundAt = fractionSize + 1); |
| 21907 | digits[0] = 0; |
| 21908 | for (var i = 1; i < roundAt; i++) digits[i] = 0; |
| 21909 | } |
| 21910 | |
| 21911 | if (digit >= 5) { |
| 21912 | if (roundAt - 1 < 0) { |
| 21913 | for (var k = 0; k > roundAt; k--) { |
| 21914 | digits.unshift(0); |
| 21915 | parsedNumber.i++; |
| 21916 | } |
| 21917 | digits.unshift(1); |
| 21918 | parsedNumber.i++; |
| 21919 | } else { |
| 21920 | digits[roundAt - 1]++; |
| 21921 | } |
| 21922 | } |
| 21923 | |
| 21924 | // Pad out with zeros to get the required fraction length |
| 21925 | for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); |
| 21926 | |
| 21927 | |
| 21928 | // Do any carrying, e.g. a digit was rounded up to 10 |
| 21929 | var carry = digits.reduceRight(function(carry, d, i, digits) { |
| 21930 | d = d + carry; |
| 21931 | digits[i] = d % 10; |
| 21932 | return Math.floor(d / 10); |
| 21933 | }, 0); |
| 21934 | if (carry) { |
| 21935 | digits.unshift(carry); |
| 21936 | parsedNumber.i++; |
| 21937 | } |
| 21938 | } |
| 21939 | |
| 21940 | /** |
no test coverage detected