* Round the parsed number to the specified number of decimal places * This function changed the parsedNumber in-place
(parsedNumber, fractionSize, minFrac, maxFrac)
| 19135 | * This function changed the parsedNumber in-place |
| 19136 | */ |
| 19137 | function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { |
| 19138 | var digits = parsedNumber.d; |
| 19139 | var fractionLen = digits.length - parsedNumber.i; |
| 19140 | |
| 19141 | // determine fractionSize if it is not specified; `+fractionSize` converts it to a number |
| 19142 | fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; |
| 19143 | |
| 19144 | // The index of the digit to where rounding is to occur |
| 19145 | var roundAt = fractionSize + parsedNumber.i; |
| 19146 | var digit = digits[roundAt]; |
| 19147 | |
| 19148 | if (roundAt > 0) { |
| 19149 | digits.splice(roundAt); |
| 19150 | } else { |
| 19151 | // We rounded to zero so reset the parsedNumber |
| 19152 | parsedNumber.i = 1; |
| 19153 | digits.length = roundAt = fractionSize + 1; |
| 19154 | for (var i=0; i < roundAt; i++) digits[i] = 0; |
| 19155 | } |
| 19156 | |
| 19157 | if (digit >= 5) digits[roundAt - 1]++; |
| 19158 | |
| 19159 | // Pad out with zeros to get the required fraction length |
| 19160 | for (; fractionLen < fractionSize; fractionLen++) digits.push(0); |
| 19161 | |
| 19162 | |
| 19163 | // Do any carrying, e.g. a digit was rounded up to 10 |
| 19164 | var carry = digits.reduceRight(function(carry, d, i, digits) { |
| 19165 | d = d + carry; |
| 19166 | digits[i] = d % 10; |
| 19167 | return Math.floor(d / 10); |
| 19168 | }, 0); |
| 19169 | if (carry) { |
| 19170 | digits.unshift(carry); |
| 19171 | parsedNumber.i++; |
| 19172 | } |
| 19173 | } |
| 19174 | |
| 19175 | /** |
| 19176 | * Format a number into a string |
no test coverage detected