Hello

I'm new to java & I am trying to convert a float to a string in my simple program. But I get an error on that line. Can you tell me why or what I need to do to fix it?

Maybe I haven't imported the right things or sumthing?

import java.io.IOException;
import java.util.Scanner; // must have this to take in input (cin)


public class Main {
    
    public Main() {
    }
    
    
    public static void main(String[] args) throws IOException {
        
        // Create scanner variable (cin variable)
        Scanner scan = new Scanner(System.in);
        
        System.out.println("\nWelcome to the Interest Calculator");
        
        char decision = 'y';
        
        while (decision == 'y' || decision == 'Y')   // cin >> decision
        {
            System.out .println("\nEnter loan amount:   ");
            float loan = scan.nextFloat();
            
            System.out.println("Enter interest rate: ");
            float rate = scan.nextFloat();
            
            System.out.println("\nLoan amount:         $" + loan);
            System.out.println("Interest rate:       " + (rate*100) + "%");
            
            float interest = (loan*rate);
            
            System.out.println("Interest:            $" + interest);
            
            System.out.println("Continue? (y/n): ");
            decision = (char)System.in.read();
        }
    }
    
    public String alter(float n) {
        /// Pre: variable n must be of type float
        /// Post: return loan amount as a string with commas inserted
        
        String number = Float.toString(number); // ERROR HERE convert float to string;
        
        number.length();
        
        return number;
    }
    
}
String number = Float.toString(number);

I think what you are trying to do is convert the number n to a string yes?

What I would do is this:

String number = new Float(n).toString();

Here I create a Float object from my float primitive, then convert it to a String. You have tried to call the toString method statically and then pass the variable number instead of n.

I always use the static methods of the String Object.

String number = String.valueOf(n);

You can also use that for various other primitive types like int, long, char, double etc.

Comments
Much neater than my suggestion :)
This article has been dead for over six months. Start a new discussion instead.