Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
floats 2 decimals
#1
Hi

I have a problem with total that is float and i have tried to make it 2 decimal but sometimes it is working and sometimes it is not working.

@property
	def get_cart_total(self):
		orderitems = self.orderitem_set.all()
		total = sum([item.get_total for item in orderitems])
		formatted_float = "{:.2f}".format(total)
		total = float(formatted_float)
		return total
Thanks.

Attached Files

Thumbnail(s)
   
Reply
#2
Python lets you throw away resolution.
import math

pi = round(math.pi, 2)
print(pi)
Output:
3.14
Why are you throwing away information? I would keep all the resolution and format the output to show two decimal places.
Reply
#3
use f-string

formatted_float = f"{total:.2f}"
Reply
#4
When working with fiance/money should use decimal module.
Can look at this Thread for tips.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  When is it safe to compare (==) two floats? Radical 4 739 Nov-12-2023, 11:53 AM
Last Post: PyDan
  Python won 't do decimals SomebodySmart 5 721 Jun-08-2023, 07:14 PM
Last Post: buran
  Get numpy ceil and floor value for nearest two decimals klllmmm 4 1,283 Jun-07-2023, 07:35 AM
Last Post: paul18fr
  Adding Decimals to classes with OOP + rounding to significant digits (ATM demo) Drone4four 7 2,314 May-04-2022, 06:15 AM
Last Post: Drone4four
  Converting decimals stylingpat 3 2,131 Mar-27-2021, 02:32 PM
Last Post: deanhystad
  rounding and floats Than999 2 3,126 Oct-26-2020, 09:36 PM
Last Post: deanhystad
  int, floats, eval menator01 2 2,449 Jun-26-2020, 09:03 PM
Last Post: menator01
  Stuck comparing two floats Tizzle 7 3,053 Jun-26-2020, 08:23 AM
Last Post: Tizzle
  rounding floats to a number of bits Skaperen 2 2,322 Sep-13-2019, 04:37 AM
Last Post: Skaperen
  comparing fractional parts of floats Skaperen 4 3,377 Mar-19-2019, 03:19 AM
Last Post: casevh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020