简体   繁体   English

在Python 3.x中保留或添加小数位

[英]Preserving or adding decimal places in Python 3.x

I am trying to return a number with 6 decimal places, regardless of what the number is. 我试图返回一个数字,保留6位小数,无论该数字是多少。

For example: 例如:

>>> a = 3/6
>>> a
0.5

How can I take a and make it 0.500000 while preserving its type as a float? 在保留其类型为float的同时,如何取a并将其设置为0.500000?

I've tried 我试过了

'{0:.6f}'.format(a)

but that returns a string. 但这返回一个字符串。 I'd like something that accomplishes this same task, but returns a float. 我想要可以完成相同任务但返回浮点数的东西。

In memory of the computer, the float is being stored as an IEEE754 object , that means it's just a bunch of binary data exposed with a given format that's nothing alike the string of the number as you write it. 在计算机内存中,浮点数被存储为IEEE754对象 ,这意味着它只是一堆以给定格式公开的二进制数据,与编写时的数字字符串完全不同。

So when you manipulate it, it's still a float and has no number of decimals after the dot. 因此,当您对其进行操作时,它仍然是浮点数,并且小数点后没有小数位数。 It's only when you display it that it does, and whatever you do, when you display it, it gets converted to a string. 只有当您显示它时,它才起作用,并且无论您做什么,当您显示它时,它都会转换为字符串。

That's when you do the conversion to string that you can specify the number of decimals to show, and you do it using the string format as you wrote. 那时,您可以进行字符串转换,可以指定要显示的小数位数,并使用编写时使用的字符串格式进行转换。

This question shows a slight misunderstanding on the nature of data types such as float and string. 这个问题表明对诸如float和string之类的数据类型的性质有一些误解。

A float in a computer has a binary representation, not a decimal one. 计算机中的浮点数具有二进制表示形式,而不是十进制形式。 The rendering to decimal that python is giving you in the console was converted to a string when it was printed, even if it's implicit by the print function. python在控制台中为您提供的十进制渲染已在打印时转换为字符串,即使该字符串已由print函数隐含。 There is no difference between how a 0.5 and 0.5000000 is stored as a float in its binary representation. 将0.5和0.5000000作为浮点数以其二进制表示形式存储之间没有区别。

When you are writing application code, it is best not to worry about the presentation until it gets to the end user where it must, somehow, be converted to a string if only implicitly. 在编写应用程序代码时,最好不要担心演示文稿,直到演示文稿到达最终用户为止,在这种情况下,如果只是隐式地将演示文稿转换为字符串。 At that point you can worry about decimal places, or even whether you want it shown in decimal at all. 那时,您可能会担心小数位,甚至根本不用十进制显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM