Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Format Numbers with Precision

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

Python practice16 minVariables & Data TypesIntermediateLast updated January 3, 2026

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

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 1

Input

format_number(2, 3)

Output

2.000

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