Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. ## Fractions

is there any standard library function to convert decimals to fractions, for example if the input is 3.14159265 the output = 22/7 ?
thanks!  Reply With Quote

3. ## Re: Fractions

Unfortunately, no. You can create a naive fraction class fairly easily, though. See Wikipedia - Repeating Decimals for a simple method to calculate the numerator and denominator given a decimal. Note that you will run into several problems:

1. Floating point numbers can also be used to hold approximations of irrational numbers (such as pi or sqrt(2)), and these have no fraction equivalent. 22/7 = 3.1428571428571 (bold part is where Pi and 22/7 deviate)

2. Floating point numbers are restricted in the precision that they can hold. Thus, even though 0.3333333... = 1/3, the floating point representation would be 0.3333333333333333 = 3333333333333333/10000000000000000. It is possible to check for some common fractions such as 1/3, but even so, the floating point arithmetic might truncate some digits differently as you perform operations, leaving something like 0.3333333333333342 (or even greater error depending on the application), which would be much more difficult to determine a fraction equivalent.

3. Integers/longs are limited to a certain maximum value. In the above example, longs were more than capable of storing both number representations. However, say you had the number 6.02214179e23 (a very useful number). A long would be unable to store the numerator for that number, even though the denominator would be 1.

There is a way to try and get around problem 3 using BigInteger, and using BigDecimal on 2 would help somewhat, but ultimately you will have the same problems when you try to compute the fraction equivalent of certain numbers (ex. 1/3 using a BigDecimal will still truncate the number of 3's you will have, but will just do so later).  Reply With Quote