Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Force calculation result as decimal
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 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"
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))"

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

C:\Users\nilamo>python -c "from decimal import Decimal; print(Decimal(0.0000006) + Decimal(0.0000008))"
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/", 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^^)


Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  testing for Decimal w/o importing decimal every time Skaperen 7 527 May-06-2019, 10:23 PM
Last Post: Skaperen

Forum Jump:

Users browsing this thread: 1 Guest(s)