Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 20

Format Numbers with Precision

Medium

16 minute session

Summary

Return a string representation of a number rounded to a specified number of decimal places, preserving trailing zeros.

Problem statement

Write format_number(num, decimals) that takes a numeric value num (int or float) and an integer decimals (>= 0). Return a string representing num rounded to exactly decimals decimal places, including trailing zeros if necessary. If decimals is not a non-negative integer, raise a ValueError. Use standard Python rounding behavior.

Task

Implement a function that formats a numeric value to a fixed number of decimal places and returns it as a string.

Examples

Two decimal places

Input

format_number(3.14159, 2)

Output

3.14

Explanation

Rounded to two decimal places.

Input format

A number num and an integer decimals passed as arguments to format_number(num, decimals).

Output format

A string representing num rounded to exactly decimals decimal places.

Constraints

- decimals is an integer and must be >= 0; otherwise raise ValueError. - Do not use external libraries. - The returned value must be a string (e.g., '2.000' for decimals=3).

Samples

Sample input 0

format_number(2, 3)

Sample output 0

2.000

Explanation 0

Integer input should be formatted with trailing zeros to match decimals.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:47 AM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.