Converting float decimal to fraction
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
:
<?php
function float2rat($n, $tolerance = 1.e-6) {
$h1=1; $h2=0;
$k1=0; $k2=1;
$b = 1/$n;
do {
$b = 1/$b;
$a = floor($b);
$aux = $h1; $h1 = $a*$h1+$h2; $h2 = $aux;
$aux = $k1; $k1 = $a*$k1+$k2; $k2 = $aux;
$b = $b-$a;
} while (abs($n-$h1/$k1) > $n*$tolerance);
return "$h1/$k1";
}
printf("%s\n", float2rat(66.66667)); # 200/3
printf("%s\n", float2rat(sqrt(2))); # 1393/985
printf("%s\n", float2rat(0.43212)); # 748/1731
I have written more about this algorithm and why it works, and even a JavaScript demo here: https://web.archive.org/web/20180731235708/http://jonisalonen.com/2012/converting-decimal-numbers-to-ratios/
PHP convert decimal into fraction and back?
I think I'd store the string representation too, as, once you run the math, you're not getting it back!
And, here's a quick-n-dirty compute function, no guarantees:
$input = '1 1/2';
$fraction = array('whole' => 0);
preg_match('/^((?P<whole>\d+)(?=\s))?(\s*)?(?P<numerator>\d+)\/(?P<denominator>\d+)$/', $input, $fraction);
$result = $fraction['whole'] + $fraction['numerator']/$fraction['denominator'];
print_r($result);die;
Oh, for completeness, add a check to make sure $fraction['denominator'] != 0
.
How to convert between decimals and fractions in PHP
When your number field contains a fractional value, PHP will actually consider it to be a string
, not a number
, and it'll therefore need to be converted to a number
before you can use it to perform arithmetic.
Since you've updated the requirements of your question, I've modified my answer to include two functions. I've written one function to convert from a fractional to decimal value, and another to convert from a decimal to a fractional value.
You can see a working example of this here: https://3v4l.org/ft0ZT
<?php
function fractionToDecimal($fraction)
{
// Split fraction into whole number and fraction components
preg_match('/^(?P<whole>\d+)?\s?((?P<numerator>\d+)\/(?P<denominator>\d+))?$/', $fraction, $components);
// Extract whole number, numerator, and denominator components
$whole = $components['whole'] ?: 0;
$numerator = $components['numerator'] ?: 0;
$denominator = $components['denominator'] ?: 0;
// Create decimal value
$decimal = $whole;
$numerator && $denominator && $decimal += ($numerator/$denominator);
return $decimal;
}
function decimalToFraction($decimal)
{
// Determine decimal precision and extrapolate multiplier required to convert to integer
$precision = strpos(strrev($decimal), '.') ?: 0;
$multiplier = pow(10, $precision);
// Calculate initial numerator and denominator
$numerator = $decimal * $multiplier;
$denominator = 1 * $multiplier;
// Extract whole number from numerator
$whole = floor($numerator / $denominator);
$numerator = $numerator % $denominator;
// Find greatest common divisor between numerator and denominator and reduce accordingly
$factor = gmp_intval(gmp_gcd($numerator, $denominator));
$numerator /= $factor;
$denominator /= $factor;
// Create fraction value
$fraction = [];
$whole && $fraction[] = $whole;
$numerator && $fraction[] = "{$numerator}/{$denominator}";
return implode(' ', $fraction);
}
// Examples
var_dump(fractionToDecimal('1/25')); // 0.04
var_dump(fractionToDecimal('2 3/4')); // 2.75
var_dump(fractionToDecimal('6/4')); // 1.5
var_dump(decimalToFraction(1.375)); // 1 3/8
var_dump(decimalToFraction(3)); // 3
var_dump(decimalToFraction(2.875)); // 2 7/8
Convert fraction to decimal in Php
This function will help you, feel free to modify the function as per your need.
<?php
echo convertToDecimal ("100/77");
function convertToDecimal ($fraction)
{
$numbers=explode("/",$fraction);
return round($numbers[0]/$numbers[1],6);
}
?>
This function will convert fraction to decimal.
How to add fractions and display the result as fraction?
function gcd($num1, $num2) {
/* finds the greatest common factor between two numbers */
if ($num1 < $num2) {
$t = $num1;
$num1 = $num2;
$num2 = $t;
}
while ($t = ($num1 % $num2) != 0) {
$num1 = $num2;
$num2 = $t;
}
return $num2;
}
public function add($temp) {
$newNum = $this->num * $temp->denum + $temp->num * $this->denum;
$newDenum = $temp->denum * $this->denum;
$gcd = gcd($newNum, $newDenum);
$newNum /= $gcd;
$newDenum /= $gcd;
return $newNum . '/' . $newDenum;
}
Convert .5 into 1/2
PHP code demo(In HTML it will work fine)
<?php
$number="10.5000";
if(preg_match("/^[1-9][0-9]*\.5[0]{0,}$/", $number))
{
echo $used = preg_replace("/\.5[0]{0,}$/", "½", $number);
}
elseif(preg_match("/^[0]*\.5[0]{0,}$/", $number))
{
echo $used = str_replace("$number", "½", $number);
}
else
{
echo $number;
}
Output:10½
How to convert decimal seconds to time with fractional seconds in PHP
Use sprintf()
function to set leading digits:
function secstotime($totalSeconds) {
$startTotalSeconds = $totalSeconds;
$hours = floor($totalSeconds / 3600);
$totalSeconds %= 3600;
$minutes = floor($totalSeconds / 60);
$seconds = $startTotalSeconds - ($minutes * 60);
return sprintf("%02d",$hours) . ":" . sprintf("%02d",$minutes) . ":" .sprintf("%.1f", $seconds);
}
//...
echo secstotime(375.844); // prints 00:06:15.8
Round up decimal number according to fraction in PHP
use this function:
function fractionRound($num,$frac) {
return ceil($num/$frac)*$frac;
}
call it this way:
echo fractionRound(( 2 * 18 )/2.98, 0.25);
it will round to the nearest 0.25 it will return 12.25
php only show decimal place if have fraction
You can use PHP round function.
http://php.net/manual/en/function.round.php
PHP Code:
<?php
echo round(10.25455, 5); // outputs: 10.25455
echo '<br/>';
echo round(10.00000, 5); // outputs: 10
How to get whole and decimal part of a number?
$n = 1.25;
$whole = floor($n); // 1
$fraction = $n - $whole; // .25
Then compare against 1/4, 1/2, 3/4, etc.
In cases of negative numbers, use this:
function NumberBreakdown($number, $returnUnsigned = false)
{
$negative = 1;
if ($number < 0)
{
$negative = -1;
$number *= -1;
}
if ($returnUnsigned){
return array(
floor($number),
($number - floor($number))
);
}
return array(
floor($number) * $negative,
($number - floor($number)) * $negative
);
}
The $returnUnsigned
stops it from making -1.25 in to -1 & -0.25
Related Topics
I Have a Base64 Encoded Png, How to Write the Image to a File in PHP
Returning First X Items from Array
How to Prevent PHP Files from Being Downloaded? and What Are Some Ways Someone Can Download Them
Which Method Is Preferred Strstr or Strpos
Automatically Refresh Token Using Google Drive API with PHP Script
PHP Soap Client That Understands Multi-Part Messages
Woocommerce Add to Cart Button Redirect to Checkout
Where to Put the PHP Artisan Migrate Command
Upload Images on Twitter Using PHP
Get Date for Monday and Friday for the Current Week (Php)
Message: Trying to Access Array Offset on Value of Type Null
How to Write to Error Log File in PHP
How to Declare a Method Static and Nonstatic in PHP
Xml Creation Using Codeigniter