Float to numerator and denominator
I'm trying to break up a float into a numerator and denominator.
For example, 1.65 would be 165/100, .5 would be 5/10. This is what I'm using:
<?php
// get the whole part
$whole = (int)$fraction_str;
// find the decimal point, and get everything after it
$decimal_position = strpos($fraction_str, '.');
$decimal = substr($fraction_str, $decimal_position + 1);
$numerator = (int)($whole . $decimal);
$denominator = pow(10, strlen($decimal));
// watch for negative on floats with no whole part
if($whole == 0 && (float)$fraction_str < 0)
$numerator *= -1;
?>
It works (so far) but is there a better way? When I start using more math operators (as opposed to string functions), I run into the classic precision problems. (Like when 1.65 turns into 1.6499999)
pr0gr4mm3r posted this at 04:35 — 9th January 2009.
He has: 1,502 posts
Joined: Sep 2006
That looks like the easiest way. Your method is the simplest of the other ones I've found. You might want to typecast it to a float first to make sure you aren't fed the right number format.
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.