Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting decimals
#1
Good morning!

If I have a variable that is let’s say 2000.846

What would be the easiest way to convert the decimals to a specific number?

If above .75 convert to .50
If above .50 convert to .25
If above .25 convert to .00
Reply
#2
Here is one way to go about it:

number = 2000.846

integer = int (number)
decimal = number - integer

if decimal > .75 : decimal = .50
elif decimal > .50 : decimal = .25
else : decimal = .00

output = integer + decimal
print (f'{output:.2f}')
stylingpat likes this post
Reply
#3
OoOooOoo thats how you split the number and the decimal up! Thank you thank you!! Dance Heart
Reply
#4
That is a way to get the decimal part of a number. You can also use the modulo operator.
decimal = 1.234 % 1
Or you can use the divmod function to get the whole and decimal parts
whole, decimal = divmod(1.234, 1)
Instead of the if statements you could use floor division (//).
number = 2000.846
whole, decimal = divmod(number, 1)
rounded = whole + (decimal // 0.25)*0.25
print (rounded)
As in everything Python there are many ways to solve almost any problem.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python won 't do decimals SomebodySmart 5 773 Jun-08-2023, 07:14 PM
Last Post: buran
  Get numpy ceil and floor value for nearest two decimals klllmmm 4 1,320 Jun-07-2023, 07:35 AM
Last Post: paul18fr
  Adding Decimals to classes with OOP + rounding to significant digits (ATM demo) Drone4four 7 2,379 May-04-2022, 06:15 AM
Last Post: Drone4four
  floats 2 decimals rwahdan 3 1,663 Dec-19-2021, 10:30 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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