diff --git a/src/rules/noMagicNumbersRule.ts b/src/rules/noMagicNumbersRule.ts index 0652319aa3b..2fb398dc6ec 100644 --- a/src/rules/noMagicNumbersRule.ts +++ b/src/rules/noMagicNumbersRule.ts @@ -15,12 +15,14 @@ * limitations under the License. */ -import { isCallExpression, isIdentifier } from "tsutils"; +import { isCallExpression, isIdentifier, isPropertyAccessExpression } from "tsutils"; import * as ts from "typescript"; import * as Lint from "../index"; import { isNegativeNumberLiteral } from "../language/utils"; +const NUMBER_METHODS = new Set(["toExponential", "toFixed", "toPrecision", "toString"]); + interface AllowedNumbersType { "allowed-numbers": number[]; } @@ -140,12 +142,17 @@ function parseOptions(options: Array): ParsedOptionsType { class NoMagicNumbersWalker extends Lint.AbstractWalker { public walk(sourceFile: ts.SourceFile) { const cb = (node: ts.Node): void => { - if ( - isCallExpression(node) && - isIdentifier(node.expression) && - node.expression.text === "parseInt" - ) { - return node.arguments.length === 0 ? undefined : cb(node.arguments[0]); + if (isCallExpression(node)) { + if (isIdentifier(node.expression) && node.expression.text === "parseInt") { + return node.arguments.length === 0 ? undefined : cb(node.arguments[0]); + } + + if ( + isPropertyAccessExpression(node.expression) && + NUMBER_METHODS.has(node.expression.name.text) + ) { + return; + } } if (node.kind === ts.SyntaxKind.NumericLiteral) { diff --git a/test/rules/no-magic-numbers/default/test.ts.lint b/test/rules/no-magic-numbers/default/test.ts.lint index cc89268912b..8cd050f2c5e 100644 --- a/test/rules/no-magic-numbers/default/test.ts.lint +++ b/test/rules/no-magic-numbers/default/test.ts.lint @@ -30,3 +30,19 @@ class A { enum Test { key = 1337, } + +const a = 0.1234567801234567890; +a.toFixed(2); +a.toFixed(5); +a.toFixed(10); + +a.toString(10); +a.toString(36); + +a.toPrecision(3) +a.toPrecision(10) +a.toPrecision(20) + +const b = 77.1234; +b.toExponential(4); +b.toExponential(2);