# 如何将数字的小数部分舍入为有效数字？

[英]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)
``````