PHP将小数转换成小数然后返回? [英] PHP convert decimal into fraction and back?
问题描述
我希望用户能够输入像这样的分数:
I want the user to be able to type in a fraction like:
1/2
2 1/4
3
并将其转换为对应的十进制数,以保存在MySQL中,这样我就可以对其进行排序并对其进行其他比较.
And convert it into its corresponding decimal, to be saved in MySQL, that way I can order by it and do other comparisons to it.
但是向用户显示时,我需要能够将小数转换回小数
But I need to be able to convert the decimal back to a fraction when showing to the user
所以基本上我需要一个将分数字符串转换为十进制的函数:
so basically I need a function that will convert fraction string to decimal:
fraction_to_decimal("2 1/4");// return 2.25
和一个可以将小数转换为派系字符串的函数:
and a function that can convert a decimal to a faction string:
decimal_to_fraction(.5); // return "1/2"
我该怎么做?
推荐答案
我想我也要存储字符串表示形式,因为一旦运行数学运算,就不会将其取回来!
I think I'd store the string representation too, as, once you run the math, you're not getting it back!
而且,这是一个快速n脏的计算函数,不能保证:
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;
为完整性起见,请添加检查以确保$fraction['denominator'] != 0
.
Oh, for completeness, add a check to make sure $fraction['denominator'] != 0
.
这篇关于PHP将小数转换成小数然后返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!