Home > front end >  getting wrong number when too many decimals
getting wrong number when too many decimals

Time:05-05

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Try using Python's in-built function range(). For example, if you only want 12 decimal spaces then use this:

range(your_variable, 12)

The second argument sets the number of decimal spaces you want.

  • Related