2

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.

2
  • 4
    Trailing zeros after the decimal point have absolutely no effect on the number represented. Just store it using any appropriate number type, and if you have a requirements to show exactly N digits to the user, simply pad the string with zeros. Commented Oct 22, 2011 at 16:49
  • @delnan: But they can have an effect on calculations using the number, especially in scientific situations. Commented Oct 22, 2011 at 17:15

3 Answers 3

6

decimal.Decimal allows you to use a specific precision.

>>> decimal.Decimal('12.000')
Decimal('12.000')
Sign up to request clarification or add additional context in comments.

Comments

2

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.)

Comments

0

You may be interested by the decimal python lib.

You can set the precision with getcontext().prec.

Comments

Your Answer

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