打印浮动到n个小数位,包括尾随0 [英] print float to n decimal places including trailing 0's

查看:141
本文介绍了打印浮动到n个小数位,包括尾随0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将浮点数打印或转换为十进制15位的字符串,即使结果有许多尾随的0例如:

<1.6>变成1.6000000000000000



我试过了(6.2,15),但是它返回了6.2000000000000002加了舍入错误

我也看到网上有不同的人把谁浮动到一个字符串,然后添加尾随0的手动,但这似乎疯了...



最好的办法是做到这一点?


对于2.6+和3.x版本的Python版本

您可以使用 str.format 方法。例子:

 >>>打印{0:.16f}。格式(1.6)
1.6000000000000001

>>>打印{0:.15f}。格式(1.6)
1.600000000000000

在第一个例子的末尾, 1 是舍入错误;发生这种情况是因为十进制数1.6的确切表示需要无限的二进制数字。由于浮点数的位数是有限的,所以数字四舍五入到一个近似值,但不是相等的值。对于2.6之前的Python版本(至少回到2.0)

你可以使用modulo-formatting语法(这也适用于Python 2.6和2.7):

 >>>打印'%.16f'%1.6 
1.6000000000000001

>>>打印'%.15f'%1.6
1.600000000000000


I need to print or convert a float number to 15 decimal place string even if the the result has many trailing 0s eg:

1.6 becomes 1.6000000000000000

I tried round(6.2,15) but it returns 6.2000000000000002 adding a rounding error

I also saw various people online who put the float into a string and then added trailing 0's manually but that seems mad...

What is the best way to do this?

解决方案

For Python versions in 2.6+ and 3.x

You can use the str.format method. Examples:

>>> print '{0:.16f}'.format(1.6)
1.6000000000000001

>>> print '{0:.15f}'.format(1.6)
1.600000000000000

Note the 1 at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.

For Python versions prior to 2.6 (at least back to 2.0)

You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):

>>> print '%.16f' % 1.6
1.6000000000000001

>>> print '%.15f' % 1.6
1.600000000000000

这篇关于打印浮动到n个小数位,包括尾随0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆