-2

So I am having a bit of trouble rounding a float in python.

This is what my output looks like

Here is your receipt:
Coffe £ 1.2
HotChocolate £ 2.0
Latte £ 3.9000000000000004
Cappucino £ 2.2
Cake £ 1.5
Pensioner Yes
Takeout Yes
Total Cost: 11.664000000000001

How would I round up the value to 2 dp?

Help would be very much appreciated.

ProTechXS
  • 57
  • 1
  • 7
  • Please read [the following answer](https://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python). If its just in printing: print("%.2f" % float) – Isdj May 29 '17 at 16:23
  • 2
    It is generally considered that `float` is unsafe for money amounts. See https://stackoverflow.com/questions/1406737/what-class-to-use-for-money-representation and https://stackoverflow.com/questions/7560455/decimals-to-2-places-for-money-in-python-3 – cdarke May 29 '17 at 16:27

2 Answers2

4

Sample examples:

>>> x = 11.664000000000001
>>> 
>>> round(x, 2)
11.66
>>> 
>>> '{:0.2f}'.format(x)
'11.66'
>>> 
>>> '%0.2f' % x
'11.66'
>>>
JkShaw
  • 1,927
  • 2
  • 13
  • 14
0

The floats has a propertie, they are non exacts, because of the architecture of the machine, python has it limitation too, try printing like:

print("%.2f" % some_float)

This question has everything you need:

Limiting floats to two decimal points

developer_hatch
  • 15,898
  • 3
  • 42
  • 75