1

So I need to cut off some decimals cases in my output.

I have the following line:

print ("O valor a pagar é de ", ***float(n3)*1.3***, " euros.")

In the area that I highlited I get to much cases... The output is something like this for example: 2,47893698236923 and I want it to show only 2 decimal cases like: 2,47.

How do I do it? And I'm using python 3.5.0

Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • @OP : caution, output is with decimal *point* no *coma* (except if you work with the locale standard module). – P. Ortiz Oct 31 '15 at 20:28

3 Answers3

2

As pointed out by BlivetWidget, floating format causes rounding not truncating.

You can use the Decimal module :

from decimal import Decimal, ROUND_DOWN

x = 2.47893698236923
print(Decimal(str(x)).quantize(Decimal('.01'), rounding=ROUND_DOWN))
print(Decimal(str(x)).quantize(Decimal('.001'), rounding=ROUND_DOWN))

output :

2.47
2.478

EDIT As the Python docs explains :

The quantize() method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places

EDIT 2

See also Truncating floats in Python

Community
  • 1
  • 1
P. Ortiz
  • 174
  • 7
  • That did not work in my python module... Traceback (most recent call last): File "C:\Users\Acer\Pictures\Ines\python\exerciocio 1.py", line 36, in print ("O valor a pagar é de ", Decimal(str(float(n3)*1.3).quatize('.01'), rounding=ROUND_DOWN), " euros.") AttributeError: 'str' object has no attribute 'quatize' – Inês Barata Feio Borges Nov 01 '15 at 13:59
  • @Ines: You misspelled `quantize`. – P. Ortiz Nov 01 '15 at 15:11
-1

Use the round() function.

print("O valor a pagar é de ", round(float(n3) * 1.3, 2), " euros.")
ddsnowboard
  • 922
  • 5
  • 13
-1

Based on the example you gave, you want to truncate a value (the other answers at this time will round the value). If you just want to truncate, I would use a string slice.

>>> num = 2.47893698236923
>>> str(num)[:str(num).find('.') + 3]
'2.47'

PS: if you don't know if there will be a decimal in there, you could use this variant:

>>> numstr = str(num)
>>> numstr[:(numstr.find('.') + 3) if numstr.find('.') else None]
'2.47'
BlivetWidget
  • 10,543
  • 1
  • 14
  • 23
  • Can whoever is downvoting this answer explain why the answer is not useful, especially considering that it's the only answer that gives the output requested by the OP? – BlivetWidget Oct 31 '15 at 20:27
  • I didn't downvote your post. But, the Op is not requering rounding because rounding 2.47893698236923 -> 2.48. EDIT you are right, .2f is rounding instead of pruning, I was not aware of this. – P. Ortiz Oct 31 '15 at 20:38
  • @P.Ortiz That's my point, all of the other answers round the value (try one or two of them), while I truncated the value as requested. (PS rounding 2.47893698236923 to two decimal places is actually 2.48) – BlivetWidget Oct 31 '15 at 20:41