| 188 | * [more] {boolean} Whether the result of division was truncated. |
| 189 | */ |
| 190 | function round(x, dp, rm, more) { |
| 191 | var xc = x.c, |
| 192 | i = x.e + dp + 1; |
| 193 | |
| 194 | if (i < xc.length) { |
| 195 | if (rm === 1) { |
| 196 | |
| 197 | // xc[i] is the digit after the digit that may be rounded up. |
| 198 | more = xc[i] >= 5; |
| 199 | } else if (rm === 2) { |
| 200 | more = xc[i] > 5 || xc[i] == 5 && |
| 201 | (more || i < 0 || xc[i + 1] !== UNDEFINED || xc[i - 1] & 1); |
| 202 | } else if (rm === 3) { |
| 203 | more = more || xc[i] !== UNDEFINED || i < 0; |
| 204 | } else { |
| 205 | more = false; |
| 206 | if (rm !== 0) throw Error(INVALID_RM); |
| 207 | } |
| 208 | |
| 209 | if (i < 1) { |
| 210 | xc.length = 1; |
| 211 | |
| 212 | if (more) { |
| 213 | |
| 214 | // 1, 0.1, 0.01, 0.001, 0.0001 etc. |
| 215 | x.e = -dp; |
| 216 | xc[0] = 1; |
| 217 | } else { |
| 218 | |
| 219 | // Zero. |
| 220 | xc[0] = x.e = 0; |
| 221 | } |
| 222 | } else { |
| 223 | |
| 224 | // Remove any digits after the required decimal places. |
| 225 | xc.length = i--; |
| 226 | |
| 227 | // Round up? |
| 228 | if (more) { |
| 229 | |
| 230 | // Rounding up may mean the previous digit has to be rounded up. |
| 231 | for (; ++xc[i] > 9;) { |
| 232 | xc[i] = 0; |
| 233 | if (!i--) { |
| 234 | ++x.e; |
| 235 | xc.unshift(1); |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | // Remove trailing zeros. |
| 241 | for (i = xc.length; !xc[--i];) xc.pop(); |
| 242 | } |
| 243 | } else if (rm < 0 || rm > 3 || rm !== ~~rm) { |
| 244 | throw Error(INVALID_RM); |
| 245 | } |
| 246 | |
| 247 | return x; |