I am trying to convert calculations keyed in by users with decimal results into fractions. For e.g.; 66.6666666667 into 66 2/3. Any pointers? Thanx in advance
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
Here is my approach to this problem, works fine with rationals numbers. http://www.carlosabundis.com/2014/03/25/converting-decimals-to-fractions-with-php-v2/
Converted Python code in answer from @APerson241 to PHP
Based upon @Joni's answer, here is what I used to pull out the whole number.
Farey fractions can be quite useful in this case.
They can be used to convert any decimal into a fraction with the lowest possible denominator.
Sorry - I don't have a prototype in PHP, so here's one in Python:
Continued fractions can be used to find rational approximations to real numbers that are "best" in a strict sense. Here's a PHP function that finds a rational approximation to a given (positive) floating point number with a relative error less than
$tolerance
:I have written more about this algorithm and why it works, and even a JavaScript demo here: http://jonisalonen.com/2012/converting-decimal-numbers-to-ratios/