我想在python中保留浮点常量的数字总数(小数点前后)。
例如,如果我想施加7: 1234.567890123的固定宽度,就会变成1234.567,而12345.678901234会变成12345.67。
在这种情况下,固定小数不起作用,因为它取决于小数点之前的数字。我也尝试了宽度选项,但它施加了一个最小的宽度,我需要一个最大。
谢谢你的意见!
发布于 2016-04-27 00:43:34
只是用你的例子,
a = 1234.567890123
b = 12345.678901234
str(a)[:8] # gives '1234.567'
str(b)[:8] # gives '12345.67'发布于 2016-04-27 00:44:53
最简单的解决方案可能是使用比数字数少一个的指数格式。
"{0:.6e}".format(1234.457890123) = '1.234568e+03'最后,我编写了这个解决方案,它可以打印浮点数和指数值,但对于大多数需求来说,这可能是不必要的。
import numpy as np
def sigprint(number,nsig):
"""
Returns a string with the given number of significant digits.
For numbers >= 1e5, and less than 0.001, it does exponential notation
This is almost what ":.3g".format(x) does, but in the case
of '{:.3g}'.format(2189), we want 2190 not 2.19e3. Also in the case of
'{:.3g}'.format(1), we want 1.00, not 1
"""
if ((abs(number) >= 1e-3) and (abs(number) < 1e5)) or number ==0:
place = decplace(number) - nsig + 1
decval = 10**place
outnum = np.round(np.float(number) / decval) * decval
## Need to get the place again in case say 0.97 was rounded up to 1.0
finalplace = decplace(outnum) - nsig + 1
if finalplace >= 0: finalplace=0
fmt='.'+str(int(abs(finalplace)))+'f'
else:
stringnsig = str(int(nsig-1))
fmt = '.'+stringnsig+'e'
outnum=number
wholefmt = "{0:"+fmt+"}"
return wholefmt.format(outnum)
def decplace(number):
"""
Finds the decimal place of the leading digit of a number. For 0, it assumes
a value of 0 (the one's digit)
"""
if number == 0:
place = 0
else:
place = np.floor(np.log10(np.abs(number)))
return place发布于 2016-04-27 01:27:27
您可以在使用小数时设置精度
这听起来好像你也想要四舍五入,但可以选择其他舍入选项,如果你愿意的话。您将创建一个上下文,其中包括精度、舍入逻辑和其他一些选项。您可以使用setcontext (使用normalize的单个数字)或使用localcontext的上下文管理器将上下文应用于所有未来的操作。
import decimal
ctx = decimal.Context(prec=7, rounding=decimal.ROUND_DOWN)
print(decimal.Decimal.from_float(1234.567890123).normalize(ctx))
print(decimal.Decimal.from_float(12345.678901234).normalize(ctx))https://stackoverflow.com/questions/36878165
复制相似问题