# 如何在Python中将数字舍入为有意义的数字

1234 – > 1000

0.12 – > 0.1

0.012 – > 0.01

0.062 – > 0.06

6253 – > 6000

1999年 – > 2000年

### 9 Solutions collect form web for “如何在Python中将数字舍入为有意义的数字”

>>> round(1234, -3) 1000.0

>>> from math import log10, floor >>> def round_to_1(x): ... return round(x, -int(floor(log10(abs(x))))) ... >>> round_to_1(0.0232) 0.02 >>> round_to_1(1234243) 1000000.0 >>> round_to_1(13) 10.0 >>> round_to_1(4) 4.0 >>> round_to_1(19) 20.0

string格式中的％g将格式化浮点数为有效数字的浮点数。 它有时会使用'e'科学记数法，所以把四舍五入的string转换回一个浮点数，然后通过％s的string格式。

>>> '%s' % float('%.1g' % 1234) '1000' >>> '%s' % float('%.1g' % 0.12) '0.1' >>> '%s' % float('%.1g' % 0.012) '0.01' >>> '%s' % float('%.1g' % 0.062) '0.06' >>> '%s' % float('%.1g' % 6253) '6000.0' >>> '%s' % float('%.1g' % 1999) '2000.0'

>>> from math import log10, floor >>> def round_sig(x, sig=2): ... return round(x, sig-int(floor(log10(abs(x))))-1) ... >>> round_sig(0.0232) 0.023 >>> round_sig(0.0232, 1) 0.02 >>> round_sig(1234243, 3) 1230000.0

from math import log10, floor def round_int(i,places): if i == 0: return 0 isign = i/abs(i) i = abs(i) if i < 1: return 0 max10exp = floor(log10(i)) if max10exp+1 < places: return i sig10pow = 10**(max10exp-places+1) floated = i*1.0/sig10pow defloated = round(floated)*sig10pow return int(defloated*isign)
def round_to_n(x, n): if not x: return 0 power = -int(math.floor(math.log10(abs(x)))) + (n - 1) factor = (10 ** power) return round(x * factor) / factor round_to_n(0.075, 1) # 0.08 round_to_n(0, 1) # 0 round_to_n(-1e15 - 1, 16) # 1000000000000001.0

round_to_n(1e15 + 1, 11) # 999999999999999.9

def round_sig(x, sig=6, small_value=1.0e-9): return round(x, sig - int(floor(log10(max(abs(x), abs(small_value))))) - 1)

>>> round(1.2322, 2) 1.23

>>> def intround(n, sigfigs): ... n = str(n) ... return n[:sigfigs] + ('0' * (len(n)-(sigfigs))) >>> intround(1234, 1) '1000' >>> intround(1234, 2)

>>> def roundall1(n, sigfigs): ... n = str(n) ... try: ... sigfigs = n.index('.') ... except ValueError: ... pass ... return intround(n, sigfigs)

>>> def roundall2(n, sigfigs): ... if type(n) is int: return intround(n, sigfigs) ... else: return round(n, sigfigs)

>>> round_to_1(1234243) 1000000.0

>>> from to_precision import to_precision >>> to_precision(1234243, 1, 'std') '1000000' >>> to_precision(1234243, 1, 'sci') '1e6' >>> to_precision(1234243, 1, 'eng') '1e6'

>>> to_precision(599, 2) '600' >>> to_precision(1164, 2) '1.2e3'

import decimal from math import log10, floor def myrounding(value , roundstyle='ROUND_HALF_UP',sig = 3): roundstyles = [ 'ROUND_05UP','ROUND_DOWN','ROUND_HALF_DOWN','ROUND_HALF_UP','ROUND_CEILING','ROUND_FLOOR','ROUND_HALF_EVEN','ROUND_UP'] power = -1 * floor(log10(abs(value))) value = '{0:f}'.format(value) #format value to string to prevent float conversion issues divided = Decimal(value) * (Decimal('10.0')**power) roundto = Decimal('10.0')**(-sig+1) if roundstyle not in roundstyles: print('roundstyle must be in list:', roundstyles) ## Could thrown an exception here if you want. return_val = decimal.Decimal(divided).quantize(roundto,rounding=roundstyle)*(decimal.Decimal(10.0)**-power) nozero = ('{0:f}'.format(return_val)).rstrip('0').rstrip('.') # strips out trailing 0 and . return decimal.Decimal(nozero) for x in list(map(float, '-1.234 1.2345 0.03 -90.25 90.34543 9123.3 111'.split())): print (x, 'rounded UP: ',myrounding(x,'ROUND_UP',3)) print (x, 'rounded normal: ',myrounding(x,sig=3))
• 为什么在Python 3中“1000000000000000（1000000000000001）”这么快？
• 搅拌器：在球体周围走动
• python re.sub组：\ number后面的数字
• JavaScript在Jinja模板中引发JSON渲染SyntaxError
• Python的基本优化模式有什么用？ （python -O）
• Python：如何将html打印成文件
• 可拆分，不可变
• 从hex编码的ASCIIstring转换为纯ASCII？
• 计算Python中字典中的关键字数量
• debugging（显示）通过SQLAlchemy发送给db的SQL命令
• 正则expression式匹配跨平台换行符