JD *_*cks 21 php decimal fractions
我希望用户能够输入如下部分:
1/2
2 1/4
3
Run Code Online (Sandbox Code Playgroud)
并将其转换为相应的十进制数,以便保存在MySQL中,这样我就可以通过它进行排序并对其进行其他比较.
但是我需要能够在向用户显示时将小数转换回一个分数
所以基本上我需要一个将分数字符串转换为十进制的函数:
fraction_to_decimal("2 1/4");// return 2.25
Run Code Online (Sandbox Code Playgroud)
和一个可以将小数转换为派系字符串的函数:
decimal_to_fraction(.5); // return "1/2"
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
mmc*_*kie 20
有时您需要找到一种方法来实现它并且可以接受舍入.因此,如果你决定为你做什么范围的舍入,你可以建立这样的函数.将小数转换为最接近匹配的小数.您可以通过添加更多要测试的分母来扩展精度.
function decToFraction($float) {
// 1/2, 1/4, 1/8, 1/16, 1/3 ,2/3, 3/4, 3/8, 5/8, 7/8, 3/16, 5/16, 7/16,
// 9/16, 11/16, 13/16, 15/16
$whole = floor ( $float );
$decimal = $float - $whole;
$leastCommonDenom = 48; // 16 * 3;
$denominators = array (2, 3, 4, 8, 16, 24, 48 );
$roundedDecimal = round ( $decimal * $leastCommonDenom ) / $leastCommonDenom;
if ($roundedDecimal == 0)
return $whole;
if ($roundedDecimal == 1)
return $whole + 1;
foreach ( $denominators as $d ) {
if ($roundedDecimal * $d == floor ( $roundedDecimal * $d )) {
$denom = $d;
break;
}
}
return ($whole == 0 ? '' : $whole) . " " . ($roundedDecimal * $denom) . "/" . $denom;
}
Run Code Online (Sandbox Code Playgroud)
Der*_*huk 19
我想我也会存储字符串表示,因为一旦你运行数学运算,你就不会收回它!
而且,这是一个快速的脏计算功能,不保证:
$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;
Run Code Online (Sandbox Code Playgroud)
哦,为了完整,添加一个检查以确保$fraction['denominator'] != 0.
可以使用PEAR的Math_Fraction类来满足您的一些需求
<?php
include "Math/Fraction.php";
$fr = new Math_Fraction(1,2);
// print as a string
// output: 1/2
echo $fr->toString();
// print as float
// output: 0.5
echo $fr->toFloat();
?>
Run Code Online (Sandbox Code Playgroud)
这是一个首先确定有效分数(尽管不一定是最简单分数)的解决方案。所以 0.05 -> 5/100。然后,它确定分子和分母的最大公约数,将其减少到最简单的分数 1/20。
function decimal_to_fraction($fraction) {
$base = floor($fraction);
$fraction -= $base;
if( $fraction == 0 ) return $base;
list($ignore, $numerator) = preg_split('/\./', $fraction, 2);
$denominator = pow(10, strlen($numerator));
$gcd = gcd($numerator, $denominator);
$fraction = ($numerator / $gcd) . '/' . ($denominator / $gcd);
if( $base > 0 ) {
return $base . ' ' . $fraction;
} else {
return $fraction;
}
}
# Borrowed from: http://www.php.net/manual/en/function.gmp-gcd.php#69189
function gcd($a,$b) {
return ($a % $b) ? gcd($b,$a % $b) : $b;
}
Run Code Online (Sandbox Code Playgroud)
这包括 gcd 的纯 PHP 实现,但如果您确定安装了 gmp 模块,则可以使用 gcd 附带的模块。
正如许多其他人指出的那样,您需要使用有理数。因此,如果您将 1/7 转换为小数,然后尝试将其转换回小数,您将不走运,因为精度丢失将阻止其返回到 1/7。就我的目的而言,这是可以接受的,因为我正在处理的所有数字(标准测量)无论如何都是有理数。