How to convert a decimal number into fraction?
You have two options:
Use
float.as_integer_ratio()
:>>> (0.25).as_integer_ratio()
(1, 4)(as of Python 3.6, you can do the same with a
decimal.Decimal()
object.)Use the
fractions.Fraction()
type:>>> from fractions import Fraction
>>> Fraction(0.25)
Fraction(1, 4)
The latter has a very helpful str()
conversion:
>>> str(Fraction(0.25))
'1/4'
>>> print Fraction(0.25)
1/4
Because floating point values can be imprecise, you can end up with 'weird' fractions; limit the denominator to 'simplify' the fraction somewhat, with Fraction.limit_denominator()
:
>>> Fraction(0.185)
Fraction(3332663724254167, 18014398509481984)
>>> Fraction(0.185).limit_denominator()
Fraction(37, 200)
If you are using Python 2.6 still, then Fraction()
doesn't yet support passing in a float
directly, but you can combine the two techniques above into:
Fraction(*0.25.as_integer_ratio())
Or you can just use the Fraction.from_float()
class method:
Fraction.from_float(0.25)
which essentially does the same thing, e.g. take the integer ratio tuple and pass that in as two separate arguments.
And a small demo with your sample values:
>>> for f in (0.25, 0.5, 1.25, 3.0):
... print f.as_integer_ratio()
... print repr(Fraction(f)), Fraction(f)
...
(1, 4)
Fraction(1, 4) 1/4
(1, 2)
Fraction(1, 2) 1/2
(5, 4)
Fraction(5, 4) 5/4
(3, 1)
Fraction(3, 1) 3
Both the fractions
module and the float.as_integer_ratio()
method are new in Python 2.6.
Convert Decimal number into Fraction
If your floating point number is x
, then the numerator of the fraction over 10000 will be the integral part of (x + 0.00005) * 10000
. It's up to you whether you want to reduce the fraction to simplest terms (i.e. divide out by the gcd of the numerator and denominator).
How to convert decimal to fractions?
You should find the greatest common divisor of the resulted numbers and divide the numerator and denominator by it.
Here is one way to do it:
public class Rational {
private int num, denom;
public Rational(double d) {
String s = String.valueOf(d);
int digitsDec = s.length() - 1 - s.indexOf('.');
int denom = 1;
for (int i = 0; i < digitsDec; i++) {
d *= 10;
denom *= 10;
}
int num = (int) Math.round(d);
int g = gcd(num, denom);
this.num = num / g;
this.denom = denom /g;
}
public Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
public String toString() {
return String.valueOf(num) + "/" + String.valueOf(denom);
}
public static int gcd(int num, int denom) {
....
}
public static void main(String[] args) {
System.out.println(new Rational(1.5));
}
}
convert decimal number to fraction in javascript or closest fraction
Your first 2 steps are reasonable.
But what you should do is for the numerator and denominator calculate the Greatest Common Divisor (GCD) and then divide the numerator and denominator with that divisor to get the fraction you want.
GCD is rather easy to calculate. Here is Euclid's algorithm:
var gcd = function(a, b) {
if (!b) return a;
return gcd(b, a % b);
};
Edit
I've added a fully working JSFiddle.
Convert a decimal number to a fraction / rational number
You can use Erik Garrison's fraction.js library to do that and more fractional operations.
var f = new Fraction(2, 10000);
console.log(f.numerator + '/' + f.denominator);
To to do .003 you can just do
var f = new Fraction(.003);
console.log(f.numerator + '/' + f.denominator);
Convert Decimal to Fraction Form method (Java)
public class Fraction {
private int numerator, denominator;
public Fraction(double decimal) {
String stringNumber = String.valueOf(decimal);
int numberDigitsDecimals = stringNumber.length() - 1 - stringNumber.indexOf('.');
int denominator = 1;
for (int i = 0; i < numberDigitsDecimals; i++) {
decimal *= 10;
denominator *= 10;
}
int numerator = (int) Math.round(decimal);
int greatestCommonFactor = greatestCommonFactor(numerator, denominator);
this.numerator = numerator / greatestCommonFactor;
this.denominator = denominator / greatestCommonFactor;
}
public String toString() {
return String.valueOf(numerator) + "/" + String.valueOf(denominator);
}
public static int greatestCommonFactor(int num, int denom) {
if (denom == 0) {
return num;
}
return greatestCommonFactor(denom, num % denom);
}
public static void main(String[] args) {
System.out.println(new Fraction(0.75));
}
}
Converting recurring decimals to fractions in Python
Here is the solution for your question:
from fractions import Fraction
res = Fraction(0.66666666666).limit_denominator()
print(res)
Converting float decimal to fraction
Continued fractions can be used to find rational approximations to real numbers that are "best" in a strict sense. Here's a PHP function that finds a rational approximation to a given (positive) floating point number with a relative error less than $tolerance
:
<?php
function float2rat($n, $tolerance = 1.e-6) {
$h1=1; $h2=0;
$k1=0; $k2=1;
$b = 1/$n;
do {
$b = 1/$b;
$a = floor($b);
$aux = $h1; $h1 = $a*$h1+$h2; $h2 = $aux;
$aux = $k1; $k1 = $a*$k1+$k2; $k2 = $aux;
$b = $b-$a;
} while (abs($n-$h1/$k1) > $n*$tolerance);
return "$h1/$k1";
}
printf("%s\n", float2rat(66.66667)); # 200/3
printf("%s\n", float2rat(sqrt(2))); # 1393/985
printf("%s\n", float2rat(0.43212)); # 748/1731
I have written more about this algorithm and why it works, and even a JavaScript demo here: https://web.archive.org/web/20180731235708/http://jonisalonen.com/2012/converting-decimal-numbers-to-ratios/
Related Topics
How to Extract Parameters from a List and Pass Them to a Function Call
Re.Findall Not Returning Full Match
Split List into Smaller Lists (Split in Half)
Importerror: No Module Named Matplotlib.Pyplot
Import Error: No Module Named Numpy
Selecting from Multi-Index Pandas
How to Extract Data from Matplotlib Plot
Python Dictionary:Typeerror: Unhashable Type: 'List'
How to Use PDFminer as a Library
How to Make Python Scripts Executable on Windows
Is There a Description of How _Cmp_ Works for Dict Objects in Python 2
Python Convert Tuple to String
Search for "Does-Not-Contain" on a Dataframe in Pandas
Ssl.Sslerror: [Ssl: Certificate_Verify_Failed] Certificate Verify Failed (_Ssl.C:749)
How to Add Items into a Numpy Array