I'm new at Java, and I'm probably just an idiot, but I need to know how to show an answer as both a fraction and a decimal. Can anyone tell me how?

Recommended Answers

All 3 Replies

Here is a way that you can do it:

public class Decifrac{
  public static void main(String[] args){
    int a = 9;
    int b = 8;
    double c = ((a * 1.0)/b) ;
    System.out.println("You could show it as a fraction like this: " + a + "/" + b);
    System.out.println("And you can show it as a decimal like this: " + c); //c is a double (Decimal value)

Where it says (a * 1.0), this is needed so it converts the number into a double, if you don't you will just get 1.0. I also think you might be able to hard code the variables a and b to be like 9.0 or something like that, or even casting one of the variables like c = ((double)a)/b;.
I am sure there is another way, but this one should suit a beginner. If you have any question feel free to ask.

What i'm trying to do is be able to plug in my variables for my equation (inverse variation) and when it gets solved have the option of having it in decimal or fraction form.

import java.util.Scanner;

class invar {
	public static void main(String[] args) {
		Scanner myScanner = new Scanner(System.in);
		double first=0;
		double second=0;
		double third=0;
		double total=0;
		char reply;
		System.out.println("What are you solving for? ");
		reply = myScanner.findInLine(".").charAt(0);
		if(reply=='Y' || reply=='y') {
			System.out.println("What is X ? ");
			second = myScanner.nextInt();
			System.out.println("What i K ? ");
			third = myScanner.nextInt();
			total = third/second;
		} else {
			if (reply=='K' || reply=='k') {
				System.out.println("What is Y ? ");
				first = myScanner.nextInt();
				System.out.println("What is X ? ");
				second = myScanner.nextInt();
				total = first*second;
			} else{
				if (reply=='X' || reply=='x') {
					System.out.println("What is Y ? ");
					first = myScanner.nextInt();
					System.out.println("What is K ? ");
					third = myScanner.nextInt();
					total= third/first;
		} if (reply!='Y' && reply!='y' && reply!='X' && reply!='x' && reply!='K' && reply!='k') {
			System.out.println("That wasn't an option.");
		} else {
	}	}

Decimal form: use DecimalFormat
Fraction Form: use modulus division and a little math.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.