Home >Backend Development >Python Tutorial >How to Round Floating-Point Numbers to One Significant Figure in Python?

How to Round Floating-Point Numbers to One Significant Figure in Python?

DDD
DDDOriginal
2024-11-16 08:57:03481browse

How to Round Floating-Point Numbers to One Significant Figure in Python?

Rounding Numbers to Significant Figures in Python

When displaying floating-point numbers in a user interface, you often need to round them to a specific number of significant figures. Python offers a convenient way to achieve this using negative numbers.

For integers, you can use negative rounding to specify the number of decimal places:

>>> round(1234, -3)
1000.0

To extend this approach to rounding a float to one significant figure, you can use the following function:

from math import log10, floor

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

This function calculates the number of decimal places to round based on the absolute value of the number and returns the rounded value.

Here are some examples of how it works:

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

Note that for floats greater than 1, you may need to convert them to integers before rounding.

The above is the detailed content of How to Round Floating-Point Numbers to One Significant Figure 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