Python - How to round float to 1 significant digit

I want to round a float to a certain number of significant digits. It is very similar to this answer: https://stackoverflow.com/a/1661212/129321 ... but instead of the usual behavior, round()it should always round. I cannot use math.floor()it because it turns a float into an int.

Basically, it 0.45should be 0.4instead 0.5. And 1945.01should be 1000.0instead 2000.0.

+4
source share
4 answers

A scientific view is like a path, but numerical methods are usually faster for me than strings. However, you get a random floating point error ...

from math import *


def roundDown(x, sigfigs=1): #towards -inf 
    exponent = floor(log10(copysign(x,1))) #we don't want to accidentally try and get an imaginary log (it won't work anyway)
    mantissa = x/10**exponent #get full precision mantissa
    # change floor here to ceil or round to round up or to zero
    mantissa = floor(mantissa * 10**(sigfigs-1)) / 10**(sigfigs-1) #round mantissa to sigfigs
    return mantissa * 10**exponent

+ inf , floor ceil round. , - , .

+2

, ,

def significant_1 (s):
    l = len(str(s))   ####make sure there is enough precision
    a = ('%.' + str(l) + 'E') % decimal.Decimal(s)
    #print (a)
    significate_d = a.split(".")[0]
    times = a.split("E")[1]

    result = int(significate_d) * (10 ** int(times))

    return result


print (significant_1(1999))

print (significant_1(1945.01))

print (significant_1(0.45))

:

1000
1000
0.4
0

, :

def convert(number, interval):
    return int(number/interval)*interval

:

1923,1000 -> 1000
12.45,0.1 -> 12.4
0
 round(number[, ndigits])

, ndigits . ndigits , . . 10 ndigits; , 0 (, , (0,5) 1,0 (-0,5) -1,0).

https://docs.python.org/2/library/functions.html#round

-2

Source: https://habr.com/ru/post/1658354/


All Articles