擅长:python、mysql、java
<p>如<a href="https://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python/3411731#3411731">this post</a>中所述,您可以使用<code>float('%.3g' % i)</code>。这会产生一个float(如果您打印它,它会自动转换为字符串)。你知道吗</p>
<p>如果要动态控制位数,可以引入一个小函数,首先创建格式化字符串。你知道吗</p>
<p>一些测试:</p>
<pre class="lang-py prettyprint-override"><code>def round_to_n_digits(num, n=3):
formatstr = '%.'+str(n)+'g'
return float(formatstr % num)
i = 4523*2345
print(float('%.3g' % i))
a = [round_to_n_digits(4523*2345, 5),
round_to_n_digits(123456789),
round_to_n_digits(0.0002443),
round_to_n_digits(0.4324)]
print (a)
</code></pre>
<p>输出:</p>
<pre><code>10600000.0
[10606000.0, 123000000.0, 0.000244, 0.432]
</code></pre>