0

I need to return a number (not a string!) that always has 2 decimal places, regardless of what number I enter. For example:

  • 86 returns 86.00
  • 3.12345 returns 3.12
  • 2.0 returns 2.00

The problem is that if I use the Python's decimal module, it returns Decimal('#'), instead of just # (I want only the number). If I instead use "%.2f" % #, it returns the number as a string, which is not what I want as I can't do any math operations on strings in Python.

xv8
  • 183
  • 2
  • 11
  • 1
    You can't return such a number. You are confusing *representation* with *value*. `86.0` is a floating point value, it will *never* be a number with two zeros after the decimal point. – Martijn Pieters Oct 13 '17 at 07:28
  • 1
    Instead, you control how the numbers are *printed*, so you control how they are converted to strings when you need to display them.. – Martijn Pieters Oct 13 '17 at 07:28

1 Answers1

0
x = 3.14159
round(x, 2)

Gives 3.14

Stuart Buckingham
  • 1,574
  • 16
  • 25
  • 1
    Rounding gives you another float object. Whole numbers won't be displayed with 2 decimals, and floating point is *not a precise representation of every possible real number*, which means that rounding to two digits *can still produce a float that is using more digits*. – Martijn Pieters Oct 13 '17 at 07:27
  • Yes but there is no type that had exactly two decimal places. The only way to be exact would be to use an int that is shifted two decimal places, but then no-one of the maths works without writing custom `__mul__` and `__div__` methods for the class, so this is the easiest way of achieving what was asked – Stuart Buckingham Oct 13 '17 at 07:31
  • The OP asked for another number. Of course a float will still use more digits, it's a float, it is never going to be exact, but it will be exact to the accuracy the OP is using. – Stuart Buckingham Oct 13 '17 at 07:33
  • 1
    What the OP asked for is *impossible*. They completely failed to understand how numbers work, confusing it with string representations. The best we can do is point to the numerous duplicates and perhaps help them understand numbers better. – Martijn Pieters Oct 13 '17 at 07:35
  • Thanks for the suggestion, however the round function only returns 2 decimal values if there are 2 or more decimal values already. So in other words, the round function would not return 2 decimal values for `2.0`. I should've also mentioned that in my original post. Its for situations like representing monetary value which typically uses 2 decimal values. – xv8 Oct 13 '17 at 20:49
  • 1
    Short, precise, and it works.The context about how numbers work is missing, but the answer is sufficient for getting two digits after a decimal! – Martin Müsli Feb 09 '23 at 08:38