-4

Using Python 2.7. If I want to subtract 120.00 - 30, I get 90.0 but I want 90.00. I've tried using the format function:

a = 120.00 - 30
format(a, '.2f')

which gives me a string of '90.00', but I don't want a string. I need a decimal with 2 precision points like: 90.00.

wolfbagel
  • 319
  • 3
  • 12
  • Then just round (in the general case, not needed here) and read up floating-point logic to understand what's going on internally. It's not really clear what you really want to achieve. Using classic floats, there is no concept for what you describe. – sascha May 07 '17 at 23:19
  • 5
    Can you write why you want this? The question is confusing, because `.00` only matters for string representation. As a number `90`, `90.0`, `90.00` are the same thing. It may be easier to answer if we know your use case. – viraptor May 07 '17 at 23:21
  • 1
    Not sure what you are asking. If you want a floating point there is no difference between 90.00 and 90.0, But if you want string then there is a difference. – Ayon Nahiyan May 07 '17 at 23:22
  • 2
    The number of zeroes displayed is a matter of formatting. If you want to perform operations to a certain precision, that’s a different question – but if you’re just formatting output, then yes, a string is the right result. – Ry- May 07 '17 at 23:22

1 Answers1

1

Float doesn't support precision configuration, only rounding and formating. You should use decimal instead:

>>> from decimal import *
>>> getcontext().prec = 2
>>> Decimal(1) / Decimal(7)
Decimal('0.14')

Python decimal: https://docs.python.org/2/library/decimal.html

Raphael
  • 1,760
  • 1
  • 12
  • 21
  • 1
    Can I use this for subtracting decimals as well? For example I want to subtract: 120.00 - 30 - .50 and I need the answer to be 89.50 – wolfbagel May 08 '17 at 01:14
  • 1
    Sure, it supports all arithmetic operations. Here`s an example: http://stackoverflow.com/a/36541853/194932 – Raphael May 08 '17 at 01:17