Let's say we have 0.33, we need to output "1/3".
If we have "0.4", we need to output "2/5".
The idea is to make it human-readable to make the user understand "x parts out of y" as a better way of understanding data.
I know that percentages is a good substitute but I was wondering if there was a simple way to do this?
I think the best way to do this is to first convert your float value to an ascii representation. In C++ you could use ostringstream or in C, you could use sprintf. Here's how it would look in C++:
A similar approach could be taken in straight C.
Afterwards you would need to check that the fraction is in lowest terms. This algorithm will give a precise answer, i.e. 0.33 would output "33/100", not "1/3." However, 0.4 would give "4/10," which when reduced to lowest terms would be "2/5." This may not be as powerful as EppStein's solution, but I believe this is more straightforward.
From Python 2.6 on there is the
fractions
module.(Quoting from the docs.)
Here is implementation for ruby http://github.com/valodzka/frac
I have found David Eppstein's find rational approximation to given real number C code to be exactly what you are asking for. Its based on the theory of continued fractions and very fast and fairly compact.
I have used versions of this customized for specific numerator and denominator limits.
You can do this in any programming language using the following steps:
Example: 0.2 =0.2 x 10^1/10^1 =2/10 =1/5
So, that can be read as '1 part out of 5'
As many people have stated you really can't convert a floating point back to a fraction (unless its extremely exact like .25). Of course you could create some type of look up for a large array of fractions and use some sort of fuzzy logic to produce the result you are looking for. Again this wouldn't be exact though and you would need to define a lower bounds of how large your want the denominator to go.
.32 < x < .34 = 1/3 or something like that.