Python-如何将浮点数舍入到1个有效数字

Alb*_*ert 5 python floating-point

我想将浮点数四舍五入为特定数量的有效数字。与此答案非常相似:https : //stackoverflow.com/a/3411435/281021, 但除了正常round()行为外,它还应始终舍入。我无法使用,math.floor()因为它会将浮点数转换为整数。

基本上,0.45应该成为0.4代替0.5。而且1945.01应该成为1000.0代替2000.0

Aar*_*ron 3

科学表示似乎是一条出路,但对我来说,数值技术通常比弦技术更快。但是,您确实偶尔会遇到浮点错误......

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
Run Code Online (Sandbox Code Playgroud)

向零或 +inf 舍入就像更改floortoceil或一样简单round。以数值方式计算尾数和指数而不是转换为字符串的另一个好处是可以轻松更改 sigfigs 的数量