Home >Backend Development >Python Tutorial >How can I round floating-point numbers to a specific number of significant figures in Python?

How can I round floating-point numbers to a specific number of significant figures in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 13:05:02999browse

How can I round floating-point numbers to a specific number of significant figures in Python?

Rounding Numbers to Significant Figures in Python

When displaying floating-point numbers in a user interface, it may be desirable to round them to a specified number of significant figures. Here's how to achieve this using Python's built-in functions and custom code.

Using Negative Exponents

To round integers to specific powers of 10, negative exponents can be used. For instance, to round 1234 to the nearest thousand, you can use:

round(1234, -3)

This yields 1000.0.

Custom Function for Rounding

To round floating-point numbers to a specific number of significant figures, a custom function can be defined. The following code defines a function called round_to_1 that rounds a number to one significant figure:

from math import log10, floor

def round_to_1(x):
    return round(x, -int(floor(log10(abs(x)))))

Here, the log10 function is used to determine the order of magnitude of x. The exponent part of the result is rounded down using floor, and the negation of this value is passed to the round function, effectively rounding to that power of 10.

Examples of Usage

The round_to_1 function can be used to round numbers as follows:

round_to_1(0.0232)  # returns 0.02
round_to_1(1234243)  # returns 1000000.0
round_to_1(13)  # returns 10.0
round_to_1(4)   # returns 4.0
round_to_1(19)  # returns 20.0

Note:

If the rounded number is greater than 1, it may need to be converted to an integer.

The above is the detailed content of How can I round floating-point numbers to a specific number of significant figures in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn