Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Number.prototype.toFixed: fixed decimal places

toFixed returns fixed-point text with exactly the requested number of digits after the decimal point.

Version: ECMAScript 3 onward; example target: Node.js 24.22.2

Syntax

number.toFixed(fractionDigits)

number.toFixed(fractionDigits) returns text with exactly fractionDigits digits after the decimal point; omitting the argument means 0. The argument undergoes ToIntegerOrInfinity, so a fraction truncates toward zero, NaN becomes 0, and -0.5 also leads to zero. The 0..100 range is checked before non-finite values are handled, so even Infinity.toFixed(101) throws RangeError.

With a valid digit count, NaN and ±Infinity return "NaN" and the corresponding infinity text. When the absolute value is at least 10**21, the method uses ordinary ToString and adds no fixed decimal places. Otherwise it chooses the nearest result, choosing the larger magnitude on a tie after separating the sign. Because Number is binary, (2.55).toFixed(1) yields "2.5"; negative zero loses its sign, while a small negative value rounded to zero can yield "-0.00".

The method has existed since ECMAScript 3, is not generic, and throws TypeError for a receiver other than a Number or boxed Number. It returns text, not a number, and does not perform locale formatting. For money, toFixed alone does not remove binary error; store the smallest unit as an integer or use an appropriate decimal type.

Examples

console.log((12.375).toFixed(2), (2.55).toFixed(1));
console.log((-0).toFixed(2), (-0.0001).toFixed(2));
console.log((1e21).toFixed(2), Infinity.toFixed(2));
try { console.log(Infinity.toFixed(101)); } catch (error) { console.log(error.name); }
try { Number.prototype.toFixed.call("1", 2); } catch (error) { console.log(error.name); }

Result

12.38 2.5
0.00 -0.00
1e+21 Infinity
RangeError
TypeError

The example shows rounding, a binary surprise, negative zero, the 10**21 threshold, and RangeError for Infinity.

Sources