# Python - 如何将浮点数舍入为1位有效数字

#### Python - How to round down a float to 1 significant digit

4 个回复

``````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
``````

``````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
``````

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

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

1 如何将Double舍入到有效数字[重复]

5 在输出时将 Python 浮点数舍入为 4 位有效数字，在不同的数字范围内

7 在Python中如何找到最低有效位数

10 python 中的有效数字舍入

2017-07-18 23:10:23 5 12202   rounding