Python Forum

Full Version: Force calculation result as decimal
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi folks,

I come here to ask you a quick question

I am a noob in python and I have a so simple problem. I looked at several python documentations, but I think my poor basic knowlegde of python doesn't permit me to find what I am looking for....so I came here^^

I am not developping a python script, but simply using the calculation feature of ptyhon, which is more powerfull than the one on script shell.
I'm doing it by calling "python -c" from linux CLI

#python -c "print 0.0000006 + 0.0000008"
1.4e-06
question is : how do I force python to have a result in decimal (example 0.xxxxxxxxxx)

Thanks a lot in advance
If you want a number formatted a certain way, then you probably want to use string formatting. Or the decimal module, depending on how exact you want it:
C:\Users\nilamo>python -c "print('{0:.10f}'.format(0.0000006 + 0.0000008))"
0.0000014000

C:\Users\nilamo>python -c "from decimal import Decimal; print(Decimal(0.0000006 + 0.0000008))"
0.000001399999999999999936647356556240762159859514213167130947113037109375

C:\Users\nilamo>python -c "from decimal import Decimal; print(Decimal(0.0000006) + Decimal(0.0000008))"
0.000001399999999999999936647356556
Hi Nilamo,

Thanks a lot for your answer.

Your first command works fine, for the 2 others it returns :

# python -c "from decimal import Decimal; print(Decimal(0.0000006) + Decimal(0.0000008))"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib64/python2.6/decimal.py", line 649, in __new__
    "First convert the float to a string")
is there no command to simply display the result that automatically stick to the number with the higher number of digit?

thx a lot
To avoid errors of floating point object representation in memory, it is better to pass strings to Decimal class, e.g.
python -c "from decimal import Decimal; print(Decimal('0.0000006') + Decimal('0.0000008'))". This likely should work in python2.6.
@vercetty92, why did you are still using Python 2.6? Constructor of Decimal class in current versions of Python, e.g. Python 3.7, could process floats directly (without errors as in your example).
Hi Scidam,
this solution is perfect to me thx a lot dude!

I am using python 2.6 because this is the version redhat provides by defaut (2.6 on el6 & 2.7 on el7). Of course we can enable the software-collection repository and install python3, but we never really had this need (the destination server is not really a development server so we avoid to install unecessary thing^^)

thx