Beta

Significant figures

Description:

Description

This kata is about rounding numbers, but not in a simple way. In mathematics, we call this concept "significant figures." Significant figures are all digits except leading zeros or trailing zeros (unless the zeros are between other digits).

Let's look at some examples:

12.355 has 5 significant figures
12450.0 has 4 significant figures
0.0123 has 3 significant figures

Task

You will create a function that rounds a given floating-point number to n significant figures. The function takes two arguments:

A float representing the number to round. An integer n, representing the number of significant figures to round to. The function should return the rounded float or int. If the input number is 0, the function must return 0. If a value has fewer than the requested n digits, it is omitted.

Examples

Assume n = 3:

12.355 rounds to 12.4
12450.0 rounds to 12400.0
0.0123 remains 0.0123
0.28 remains 0.28

Notes

  1. Rounding Behavior: The function should use Python's default rounding strategy: "round half to even" (also known as bankers' rounding). For more information, you can refer to this Rounding Half to Even.

  2. Floating-Point Precision: In some solutions, you may encounter something called the "floating-point problem." This is a common issue when working with floating-point numbers in programming.

Good luck, and happy coding!

Mathematics

Stats:

CreatedJan 7, 2025
PublishedJan 7, 2025
Warriors Trained18
Total Skips0
Total Code Submissions192
Total Times Completed13
Python Completions13
Total Stars0
% of votes with a positive feedback rating30% of 5
Total "Very Satisfied" Votes1
Total "Somewhat Satisfied" Votes1
Total "Not Satisfied" Votes3
Total Rank Assessments6
Average Assessed Rank
7 kyu
Highest Assessed Rank
6 kyu
Lowest Assessed Rank
7 kyu
Ad
Contributors
  • furczak Avatar
Ad