PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

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

 August 11, 2022     decimal, precision, python, python-3.x     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing