How to Format Fractions in Java
By default, Java displays a fractional number as a decimal, but you can use the FractionFormat number to display a fraction format. Java includes a "FractionFormat" library function you can use to automatically reduce the fraction and set up two numbers with the division character in between the two numbers. The FractionFormat function makes it more convenient to work with precision numbers.
Instructions
-
-
1
Right-click the Java file you want to edit and select "Open With." Click the Java editor in the popup list of compilers.
-
2
Create a fraction. You use the "Fraction" function to set up your fraction number. The following code creates the fraction "1/2" or ".5" in decimal notation:
Fraction fract = new Fraction(1, 2);
For numbers greater than one, the entire fraction is shown. For instance, the following fraction function displays "11/2":
Fraction fract = new Fraction(11, 2);
To display "5 1/2" instead of "11/2," use the following code:
MixedFraction mixed = new MixedFraction(5,1,2)
-
-
3
Format the fraction. The following code shows you how to format the fraction with the division character:
FractionFormat f = new FractionFormat(fract);
string formatted_fraction = f.format(fract);
The first line statement creates a variable and assigns it to the "FractionFormat" class. The variable is then used to format the fraction from step two and assigns the result to the string "formatted_fraction."
-
1