简体   繁体   中英

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.

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?

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.

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.

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. There is no difference between how a 0.5 and 0.5000000 is stored as a float in its binary representation.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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