似乎没有内置的字符串格式化技巧,它使您可以(1)打印浮点数的第一个有效数字出现在小数点后15位,以及(2)不使用科学计数法。这样就可以进行手动字符串 *** 作了。
在下面,我使用该
decimal模块从浮点数中提取十进制数字。该
float_to_decimal函数用于将浮点数转换为
Decimal对象。明显的方法
decimal.Decimal(str(f))是错误的,因为
str(f)会丢失大量数字。
float_to_decimal从十进制模块的文档中删除。
一旦将十进制数字作为整数元组获得,下面的代码就可以完成以下工作:截取所需数量的有效数字,如果需要,将其四舍五入,将数字连成字符串,在符号上加钉,然后将小数点,并在适当的时候向左或向右零。
在底部,您会发现一些我用来测试该
f功能的案例。
import decimaldef float_to_decimal(f): # http://docs.python.org/library/decimal.html#decimal-faq "Convert a floating point number to a Decimal with no loss of information" n, d = f.as_integer_ratio() numerator, denominator = decimal.Decimal(n), decimal.Decimal(d) ctx = decimal.Context(prec=60) result = ctx.divide(numerator, denominator) while ctx.flags[decimal.Inexact]: ctx.flags[decimal.Inexact] = False ctx.prec *= 2 result = ctx.divide(numerator, denominator) return resultdef f(number, sigfig): # http://stackoverflow.com/questions/2663612/nicely-representing-a-floating-point-number-in-python/2663623#2663623 assert(sigfig>0) try: d=decimal.Decimal(number) except TypeError: d=float_to_decimal(float(number)) sign,digits,exponent=d.as_tuple() if len(digits) < sigfig: digits = list(digits) digits.extend([0] * (sigfig - len(digits))) shift=d.adjusted() result=int(''.join(map(str,digits[:sigfig]))) # Round the result if len(digits)>sigfig and digits[sigfig]>=5: result+=1 result=list(str(result)) # Rounding can change the length of result # If so, adjust shift shift+=len(result)-sigfig # reset len of result to sigfig result=result[:sigfig] if shift >= sigfig-1: # Tack more zeros on the end result+=['0']*(shift-sigfig+1) elif 0<=shift: # Place the decimal point in between digits result.insert(shift+1,'.') else: # Tack zeros on the front assert(shift<0) result=['0.']+['0']*(-shift-1)+result if sign: result.insert(0,'-') return ''.join(result)if __name__=='__main__': tests=[ (0.1, 1, '0.1'), (0.0000000000368568, 2,'0.000000000037'), (0.00000000000000000000368568, 2,'0.0000000000000000000037'), (756867, 3, '757000'), (-756867, 3, '-757000'), (-756867, 1, '-800000'), (0.0999999999999,1,'0.1'), (0.00999999999999,1,'0.01'), (0.00999999999999,2,'0.010'), (0.0099,2,'0.0099'), (1.999999999999,1,'2'), (1.999999999999,2,'2.0'), (34500000000000000000000, 17, '34500000000000000000000'), ('34500000000000000000000', 17, '34500000000000000000000'), (756867, 7, '756867.0'), ] for number,sigfig,answer in tests: try: result=f(number,sigfig) assert(result==answer) print(result) except AssertionError: print('Error',number,sigfig,result,answer)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)