MCPcopy Create free account
hub / github.com/angular/angular / roundNumber

Function roundNumber

packages/common/src/i18n/format_number.ts:461–533  ·  view source on GitHub ↗

* Round the parsed number to the specified number of decimal places * This function changes the parsedNumber in-place

(parsedNumber: ParsedNumber, minFrac: number, maxFrac: number)

Source from the content-addressed store, hash-verified

459 * This function changes the parsedNumber in-place
460 */
461function roundNumber(parsedNumber: ParsedNumber, minFrac: number, maxFrac: number) {
462 if (minFrac > maxFrac) {
463 throw new RuntimeError(
464 RuntimeErrorCode.INVALID_NUMBER_OF_DIGITS_AFTER_FRACTION,
465 ngDevMode &&
466 `The minimum number of digits after fraction (${minFrac}) is higher than the maximum (${maxFrac}).`,
467 );
468 }
469
470 let digits = parsedNumber.digits;
471 let fractionLen = digits.length - parsedNumber.integerLen;
472 const fractionSize = Math.min(Math.max(minFrac, fractionLen), maxFrac);
473
474 // The index of the digit to where rounding is to occur
475 let roundAt = fractionSize + parsedNumber.integerLen;
476 let digit = digits[roundAt];
477
478 if (roundAt > 0) {
479 // Drop fractional digits beyond `roundAt`
480 digits.splice(Math.max(parsedNumber.integerLen, roundAt));
481
482 // Set non-fractional digits beyond `roundAt` to 0
483 for (let j = roundAt; j < digits.length; j++) {
484 digits[j] = 0;
485 }
486 } else {
487 // We rounded to zero so reset the parsedNumber
488 fractionLen = Math.max(0, fractionLen);
489 parsedNumber.integerLen = 1;
490 digits.length = Math.max(1, (roundAt = fractionSize + 1));
491 digits[0] = 0;
492 for (let i = 1; i < roundAt; i++) digits[i] = 0;
493 }
494
495 if (digit >= 5) {
496 if (roundAt - 1 < 0) {
497 for (let k = 0; k > roundAt; k--) {
498 digits.unshift(0);
499 parsedNumber.integerLen++;
500 }
501 digits.unshift(1);
502 parsedNumber.integerLen++;
503 } else {
504 digits[roundAt - 1]++;
505 }
506 }
507
508 // Pad out with zeros to get the required fraction length
509 for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
510
511 let dropTrailingZeros = fractionSize !== 0;
512 // Minimal length = nb of decimals required + current nb of integers
513 // Any number besides that is optional and can be removed if it's a trailing 0
514 const minLen = minFrac + parsedNumber.integerLen;
515 // Do any carrying, e.g. a digit was rounded up to 10
516 const carry = digits.reduceRight(function (carry, d, i, digits) {
517 d = d + carry;
518 digits[i] = d < 10 ? d : d - 10; // d % 10

Callers 1

Calls 4

popMethod · 0.80
minMethod · 0.45
maxMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected