1

In this program, I am asking the user to input two datetime, and I convert the differences between the two date times into several floats. difference_days is one of the float of total difference in days. so basically, I am writing this in for loop part of my code is below:

if difference_days.is_integer():
        print(f'The difference is {int(difference_days)} days.')
else:
        hours = (difference_days - int(difference_days))*24.0
        print(int(difference_days))
        print(difference_days)
        print(difference_days - int(difference_days))
        print(hours)
        if difference_hours.is_integer():
            print(f'The difference is {int(difference_days)} days and {int(hours)} hours.')
        else:
        ...  # other codes that handle minutes, seconds, microseconds

I did not post all the codes, because I think there's something wrong with the calculation in python. so those print statements between hours and the second if statement is just for test, and below is the output:

91
91.95833333333333
0.9583333333333286
22.999999999999886

I was confused why the third one starts to have more decimal places in the end while the second doesn't. How should I fix that? I would like it to only display the 12 decimals.

czzz0414
  • 67
  • 6
  • This is how floats work in computers. They are inaccurate. Just like we cannot represent 0.3333... exactly in our decimal system, binary system cannot represent a lot of integers and fixed decimals precisely. So, 0.3 maybe stored as 2.9999 on your computer. Therefore, when dealing with floats, when you are to output them, either round them to the nearest whole integer, or format them to some fixed decimal points. – akaAbdullahMateen May 05 '22 at 02:39

3 Answers3

1

You can just use the format() function, and convert it to a floating point, like this:

float(format(difference_days,".12f"))

This will return difference_days as a floating point with 12 decimals

Coolcreeper
  • 134
  • 9
0

Well I guess I just found the solution, so I did the following, but any better ideas?

from decimal import *
getcontext().prec = 12
hours = (Decimal(difference_days) - int(difference_days))*24
czzz0414
  • 67
  • 6
  • You could always just use `round` on the `float` result. It's not always reliable for the reasons given in the link in the comments to your question, but it will be for values that are close to an integer. – Mark Ransom May 05 '22 at 02:34
  • Please mark your own solution as accepted, so people can know if your question is already answered. – akaAbdullahMateen May 05 '22 at 02:41
0

Floating points can't be perfectly represented in binary, so you will always have the weird error at the end.

Why are floating point numbers inaccurate?

But you can print the 12 digits of the decimal with:

>>> x = 0.9583333333333286
>>> f'{x:.12f}'
'0.958333333333'
>>> float(f'{x:.12f}')
0.958333333333
Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29