Python Forum
Adding Decimals to classes with OOP + rounding to significant digits (ATM demo)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding Decimals to classes with OOP + rounding to significant digits (ATM demo)
#2
The round context isn't used here because you've passed in a float initially. That float doesn't represent exactly what you want and is already higher than the target. If you want to be exact, you have to pass in a string and let Decimal do the conversion.

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> Decimal(.505) #.505 isn't exact
Decimal('0.50500000000000000444089209850062616169452667236328125') #Not "5.05".  Is closer to 5.1
>>> round(Decimal(.505),2)
Decimal('0.51')
 
# Instead of float, pass in a string. '.505' is exact.
>>> Decimal('.505')
Decimal('0.505')
>>> round(Decimal('.505'),2) # now the context matters
Decimal('0.50')
>>> decimal.getcontext().rounding = decimal.ROUND_HALF_UP
>>> round(Decimal('.505'),2)
Decimal('0.51')
Drone4four likes this post
Reply


Messages In This Thread
RE: Adding Decimals to classes with OOP + rounding to significant digits (ATM demo) - by bowlofred - Apr-22-2022, 03:29 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python won 't do decimals SomebodySmart 5 1,835 Jun-08-2023, 07:14 PM
Last Post: buran
  Get numpy ceil and floor value for nearest two decimals klllmmm 4 3,462 Jun-07-2023, 07:35 AM
Last Post: paul18fr
  need help rounding joseph202020 7 2,720 Feb-21-2023, 08:13 PM
Last Post: joseph202020
  from numpy array to csv - rounding SchroedingersLion 6 6,284 Nov-14-2022, 09:09 PM
Last Post: deanhystad
  floats 2 decimals rwahdan 3 2,442 Dec-19-2021, 10:30 PM
Last Post: snippsat
  Random data generation sum to 1 by rounding juniorcoder 9 5,636 Oct-20-2021, 03:36 PM
Last Post: deanhystad
  Rounding issue kmll 1 2,226 Oct-08-2021, 10:35 AM
Last Post: Yoriz
  Converting decimals stylingpat 3 3,101 Mar-27-2021, 02:32 PM
Last Post: deanhystad
  Not rounding to desired decimal places? pprod 2 3,309 Mar-05-2021, 11:11 AM
Last Post: pprod
  Decimal Rounding error project_science 4 3,896 Jan-06-2021, 03:14 PM
Last Post: project_science

Forum Jump:

User Panel Messages

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