如何在PHP中拆分float? [英] How to split float in PHP?
本文介绍了如何在PHP中拆分float?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有12.054,我想将其拆分为三个变量,例如 $ whole_number = 12
$ numerator = 54
和 $ denominator = 1000 代码>.你能帮我吗?
Let's say we have 12.054 and I want to split it to three variables like $whole_number=12
$numerator=54
and $denominator=1000
. Could you help me?
推荐答案
一种直截了当的方法-不太学术,但它适用于PHP;-):
A straight-forward approach - not very academic, but it works for PHP ;-):
$float = 12.054;
$parts = explode('.', (string)$float);
$whole_number = $parts[0];
$numerator = trim($parts[1], '0');
$denominator = pow(10, strlen(rtrim($parts[1], '0')));
可能还需要做更多的工作来确保边缘情况也可以工作(跟踪 0
s,根本没有小数部分,等等).
Some more work might be needed to ensure that edge case work too (trailing 0
s, no decimal part at all, etc.).
这篇关于如何在PHP中拆分float?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文