{"record":{"id":"6741dce92af47dfc","repo":"karatelabs/karate","slug":"toprecision-precision-must-be-between-1-and-100","errorCode":null,"errorMessage":"toPrecision() precision must be between 1 and 100","messagePattern":"toPrecision\\(\\) precision must be between 1 and 100","errorType":"exception","errorClass":"JsErrorException","httpStatus":null,"severity":"error","filePath":"karate-js/src/main/java/io/karatelabs/js/JsNumberPrototype.java","lineNumber":130,"sourceCode":"        }\n        return JsScalars.toFixed(d, digits);\n    }\n\n    private Object toPrecision(Context context, Object[] args) {\n        double d = thisNumber(context).doubleValue();\n        // Absent / undefined precision: spec returns ToString(x) — no range check.\n        if (args.length == 0 || args[0] == Terms.UNDEFINED) {\n            return Terms.numberToString(d);\n        }\n        if (args[0] instanceof java.math.BigInteger) {\n            throw JsErrorException.typeError(\"Cannot convert a BigInt to a number\");\n        }\n        int precision = toIntegerArg(args[0], context);\n        if (Double.isNaN(d)) return \"NaN\";\n        if (d == Double.POSITIVE_INFINITY) return \"Infinity\";\n        if (d == Double.NEGATIVE_INFINITY) return \"-Infinity\";\n        if (precision < 1 || precision > 100) {\n            throw JsErrorException.rangeError(\"toPrecision() precision must be between 1 and 100\");\n        }\n        if (d == 0.0) {\n            // Spec §21.1.3.4: zero uses fixed notation with (precision - 1) trailing zeros\n            // after the decimal point. -0 stringifies as \"0\" (sign elided for the zero\n            // mantissa per Number::toString §6.1.6.1.13).\n            if (precision == 1) return \"0\";\n            StringBuilder sb = new StringBuilder(precision + 2);\n            sb.append(\"0.\");\n            for (int i = 1; i < precision; i++) sb.append('0');\n            return sb.toString();\n        }\n        BigDecimal bd = new BigDecimal(d);\n        bd = bd.round(new java.math.MathContext(precision, RoundingMode.HALF_UP));\n        String result = bd.toString();\n        // BigDecimal.toString uses scientific form for very large / small values; JS\n        // switches between plain and exponential at |d| < 1e-6 or |d| >= 10^precision.\n        if (result.contains(\"E\") || result.contains(\"e\")) {\n            return result.replace('E', 'e');","sourceCodeStart":112,"sourceCodeEnd":148,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-js/src/main/java/io/karatelabs/js/JsNumberPrototype.java#L112-L148","documentation":"Number.prototype.toPrecision requires the precision argument to be within 1–100 (spec allows 1–2^53-1; this engine clamps to 100). Values outside the range are rejected with a RangeError before formatting proceeds.","triggerScenarios":"Calling n.toPrecision(p) where p is a Number less than 1 (including 0, negatives, NaN-like values that convert to 0) or greater than 100.","commonSituations":"Dynamically computed precision from user input or config; off-by-one code passing digit counts; porting code from engines with a wider allowed range.","solutions":["Clamp or validate the precision to the 1–100 range before calling toPrecision","Use toFixed(digits) if you intended fixed decimals and can accept its semantics","Remove the argument entirely if you just want round-trip ToString behavior"],"exampleFix":"// before\nvar s = n.toPrecision(p); // p may be 0 or 150\n// after\nvar p2 = Math.min(100, Math.max(1, p | 0));\nvar s = n.toPrecision(p2);","handlingStrategy":"validation","validationCode":"if (!Number.isInteger(p) || p < 1 || p > 100) throw new RangeError('precision must be 1..100');","typeGuard":"function isValidPrecision(p) { return typeof p === 'number' && Number.isInteger(p) && p >= 1 && p <= 100; }","tryCatchPattern":"try { s = n.toPrecision(p); } catch (e) { if (e instanceof RangeError) { s = n.toPrecision(Math.min(100, Math.max(1, p))); } else { throw e; } }","preventionTips":["Clamp dynamic precision values before formatting","Never pass user-supplied precision unvalidated","Remember this engine caps precision at 100"],"tags":["javascript","rangeerror","karate-js","number-formatting"],"backgroundTag":"value-out-of-range","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-16T19:17:19.609Z"}