Format Decimal with toFixed()
Write a JavaScript function that takes a decimal number and a number of decimal places, and returns the number formatted with exactly that many decimal places as a string using toFixed(). The toFixed() method formats a number using fixed-point notation.
Number.prototype.toFixed() is a JavaScript-specific method that rounds a number to a specified number of decimal places and returns the result as a string. Unlike toPrecision() which formats to a specified total number of significant digits, toFixed() guarantees exactly n digits after the decimal point, padding with zeros if necessary.
The toFixed() method handles rounding automatically: 1.236.toFixed(2) returns "1.24". It also handles edge cases like very large numbers (returns exponential notation for numbers outside the safe integer range). The result is a string, not a number, because formatted output often requires leading/trailing zeros that would be lost in numeric representation.
Time complexity is O(1) as the operation is performed by the JavaScript engine's internal number formatting routines. The method is widely supported in all modern JavaScript environments.
Edge cases include negative numbers (the minus sign is preserved), zero decimal places (returns an integer as string), very large or very small numbers, and ensuring the returned type is string.
Example Input & Output
Integer with 1 decimal
Rounded down
Rounded up
Pi rounded to 2 decimals
Padded with zeros to 3 decimals
Algorithm Flow

Solution Approach
Best Answers
function solution(num, digits) {
return num.toFixed(digits);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
