1
votes

When printing a floating point variable in Python 3 like this:

str(1318516946165810000000000.123123123)

The output is:

1.31851694616581e+24

Is there a simple way in the standard lib (not Numpy) to print the same thing with only 32 bit float precision? (or more general any precision)

Be aware precision != places, like in Decimal

EDIT

The result should should be a string like str does but with a limited precision for example: 32 bit representation of the above float:

1.31851e+24
1
You mean you want to truncate the decimal representation of a float so that it doesn't give a false impression of accuracy? - that other guy
Yes, while still ensuring that the result would represent a valid 32 bit float (or any bit precision, like 24 bit), the goal is a string and not the actual python float. I hopend that there would be another way than to manually parse the string again and ensuring said restricitions - compulsoryRegistrationFTW
So you want a lossless function that can turn a float into a string and back? Does it have to be human readable? - that other guy
I'm gonna edit the question to clarify - compulsoryRegistrationFTW
-Done (filler text to make comment length long enough) - compulsoryRegistrationFTW

1 Answers

1
votes

I may have misunderstood, but is using format with a suitable precision modifier what you are asking for?

>>> "{0:6g}".format(1.31851694616581e24)
'1.31852e+24'

Change the 6 to control the number of significant figures