1

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
5
  • You mean you want to truncate the decimal representation of a float so that it doesn't give a false impression of accuracy? Commented Aug 12, 2014 at 20:06
  • 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 Commented Aug 12, 2014 at 20:12
  • So you want a lossless function that can turn a float into a string and back? Does it have to be human readable? Commented Aug 12, 2014 at 20:17
  • I'm gonna edit the question to clarify Commented Aug 12, 2014 at 20:20
  • -Done (filler text to make comment length long enough) Commented Aug 12, 2014 at 20:25

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

'g' rounds the number to x significant digits (not bits), does not guarantee a valid representation for a 32-bit float, see docs.python.org/3/library/… for details, what could happen is that the float would have a higher or lower value with 6 digits than would be allowed for a x-bit float, none of the format string modifiers looks for bit length
OK, thanks for the clarification, sorry my answer's not a lot of help to you.
But it can be used in my use case when no further validation is required and a small loss of precision can be ignored, accepting as 'near enough' because there seems no sensible one-liner in the standard lib

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.