Skip to content
Advertisement

Converting a string with a leading special character into a double?

I’m at the beginning of my Java journey, and have run into a little problem that I’m having a little difficulty figuring out.

// Buffered Reader - Cost Per Employee

    BufferedReader in3 = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Cost per employee?");
    CostPerEmployee = in3.readLine();
    CostPerEmployeeD = Double.parseDouble(CostPerEmployee);
    System.out.println("Each employee costs $" + CostPerEmployeeD +".");

I am looking to be able to convert the string input into a double even if it contains a leading “$” character. I am currently running into a NumberFormatException.

Unsure of how to utilize try, catch, and finally statements (if they’re at all applicable here).

Thanks in advance!

Advertisement

Answer

Java’s String class offers many methods for manipulating strings. One such method is the replace() method, which allows you to replace all instances of one string with another. This method takes 2 arguments, the target string and the replacement string. You can remove the target string by simply passing an empty string for the replacement string. For example:

"$123.5".replace("$", "")

Would produce:

"123.5"

Using this, we can update your code by adding only one method call:

BufferedReader in3 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Cost per employee?");

// Notice the call to replace() on this line:
CostPerEmployee = in3.readLine().replace("$", "");

CostPerEmployeeD = Double.parseDouble(CostPerEmployee);
System.out.println("Each employee costs $" + CostPerEmployeeD +".");

Please note that CostPerEmployee and CostPerEmployeeD are not defined in the code block you provided, and you have not handled the IOException thrown by the readLine() method. I am assuming that this code block is from a larger program, where these problems are resolved. In the future, a minimal, reproducible example can help clear these things up.

Advertisement