[英]How to round number's fractional part to significant figures?
I'd like to automatically round numbers to x significant figures, but only their fractional part.我想自动将数字四舍五入到x有效数字,但只有它们的小数部分。
Desired output:期望的输出:
123 >>> 123.00
123.123 >>> 123.12
1.12 >>> 1.12
0.1 >>> 0.10
0.1234 >>> 0.12
0.01234 >>> 0.012
0.0001254 >>> 0.00013
I'm trying to achieve the most simple solution.我正在尝试实现最简单的解决方案。
I've figured out such a solution:我想出了这样的解决方案:
def round_to_frac_sigfig(num, sigfigs):
sigfig_pos = int(floor(log10(abs(num))))
if sigfig_pos >= 0:
formatter = "{:.%df}" % sigfigs
return formatter.format(num)
else:
ndigits = -sigfig_pos + sigfigs - 1
formatter = "{:.%df}" % ndigits
return formatter.format(num)
If you don't care about the trailing zeros , here's a shorter solution:如果您不关心结尾的zeros ,这里有一个更短的解决方案:
def round_to_frac_sigfig(num, sigfigs):
sigfig_pos = int(floor(log10(abs(num))))
if sigfig_pos >= 0:
return round(num, sigfigs)
else:
return round(num, -sigfig_pos + sigfigs - 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.