Thursday, August 11, 2022

[FIXED] How can I round up the number of periodic digits?

Issue

I have two numbers, one I get by calculating it and the other one I bring it from the database.

calculated = 2.183333333333333
database   = 2.18333333333333

But when I compare them to know if they are the same, I return False when it should be True.

There is some way to limit the number of periodic numbers, but not to affect decimals that are not periodic, for example:

2.1748888888888 -> 2.1748
1.23333333      -> 1.23

Solution

You could use the math.isclose method:

>>> from math import isclose
>>> calculated = 2.183333333333333
>>> database   = 2.18333333333333
>>> isclose(calculated, database)
True

This allows for setting the relative tolerance and minimum absolute tolerance as well refer to the docs for more explanation.



Answered By - Jab
Answer Checked By - David Marino (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.