Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print floating point numbers as it is without any truncation in python?

Tags:

python

I have some number 0.0000002345E^-60. I want to print the floating point value as it is. What is the way to do it? print %f truncates it to 6 digits. Also %n.nf gives fixed numbers. What is the way to print without truncation.

like image 923
user2793286 Avatar asked Nov 18 '13 13:11

user2793286


People also ask

How do you print floating numbers in Python?

To print float values with two decimal places in Python, use the str. format() with “{:. 2f}” as str.

How do you print a float without scientific notation in Python?

Use a formatted string literal to print a float without scientific notation, e.g. print(f'{num:. 8f}') . You can use an expression in the f-string to print the float without scientific notation, with the specified number of decimal places.

How do you print a float value without a decimal in Python?

Solution 1: int() Python's built-in function int(x) converts any float number x to an integer by truncating it towards 0. For example, positive int(1.999) will be truncated to 1 and negative int(-1.999) to -1 .

How do I stop truncation in Python?

You can control whether to truncate or not by setting the parameter threshold with numpy. set_printoptions() .


1 Answers

Like this?

>>> print('{:.100f}'.format(0.0000002345E-60))
0.0000000000000000000000000000000000000000000000000000000000000000002344999999999999860343602938602754

As you might notice from the output, it’s not really that clear how you want to do it. Due to the float representation you lose precision and can’t really represent the number precisely. As such it’s not really clear where you want the number to stop displaying.

Also note that the exponential representation is often used to more explicitly show the number of significant digits the number has.

You could also use decimal to not lose the precision due to binary float truncation:

>>> from decimal import Decimal
>>> d = Decimal('0.0000002345E-60')
>>> p = abs(d.as_tuple().exponent)
>>> print(('{:.%df}' % p).format(d))
0.0000000000000000000000000000000000000000000000000000000000000000002345
like image 190
poke Avatar answered Oct 18 '22 21:10

poke