Reputation:
I have a string:
x = "12.000"
And I want it to convert it to digits. However, I have used int, float, and others but I only get 12.0
and i want to keep all the zeroes. Please help!
I want x = 12.000
as a result.
Upvotes: 2
Views: 670
Reputation: 94485
If you really want to perform calculations that take precision into account, the easiest way is to probably to use the uncertainties module. Here is an example
>>> import uncertainties
>>> x = uncertainties.ufloat('12.000')
>>> x
12.0+/-0.001
>>> print 2*x
24.0+/-0.002
The uncertainties module transparently handles uncertainties (precision) for you, whatever the complexity of the mathematical expressions involved.
The decimal module, on the other hand, does not handle uncertainties, but instead sets the number of digits after the decimal point: you can't trust all the digits given by the decimal module. Thus,
>>> 100*decimal.Decimal('12.1')
Decimal('1210.0')
whereas 100*(12.1±0.1) = 1210±10 (not 1210.0±0.1):
>>> 100*uncertainties.ufloat('12.1')
1210.0+/-10.0
Thus, the decimal module gives '1210.0' even though the precision on 100*(12.1±0.1) is 100 times larger than 0.1.
So, if you want numbers that have a fixed number of digits after the decimal point (like for accounting applications), the decimal module is good; if you instead need to perform calculations with uncertainties, then the uncertainties module is appropriate.
(Disclaimer: I'm the author of the uncertainties module.)
Upvotes: 2
Reputation: 3157
You may be interested by the decimal python lib.
You can set the precision with getcontext().prec
.
Upvotes: 0
Reputation: 798666
decimal.Decimal
allows you to use a specific precision.
>>> decimal.Decimal('12.000')
Decimal('12.000')
Upvotes: 6