I am trying to read 'Dollar' values. Here is the code which reads the values from the keyboard : *********** System.out.print("Enter the cost of the product : "); BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in)); String Input = consoleIn.readLine(); ActualCost = Double.parseDouble(Input); ********** This works fine except when I preceede the numbers with a '$' sign. Is there a turnaround for this. I tried using 'NumberFormat',no luck tho. What am I missing ?
Hello, Double.parseDouble(String) is looking for a number only - it doesn't know what to do with a dollar sign. You could parse the input String and remove any dollar signs before you do a Double.parseDouble(String). Look at the String documentation and the subString(int) method. You could still have troubles even after removing the '$' - what if the input String were "$$123.34c"? You might want to explore catching exceptions. Good Luck, -Dirk Schreckmann
Actually you should use a NumberFormat object. NumberFormat cf = NumberFormat.getCurrencyInstance(); //then some optional calls to set up your exact currency format patterns, or use the locale defaults. Then... Number parsedNumber = cf.parse(input ); //PLEASE DO NOT CAPITALIZE YOUR VARIABLE NAMES, THEY LOOK LIKE THEY ARE CLASS IDENTIFIERS. Then you can call various methods of Number to get out an actual number...probably parsedNumber.doubleValue();
Joined: Dec 10, 2001
Hello, Yep, I prefer that style also. Though, were I a beginner, I'd tell you to take a hike trying to get me to use an Abstract class and all that other jazz. And you still could have issues with exception handling: NumberFormat.parse(String) throws ParseException if the beginning of the specified string cannot be parsed. Good Luck, -Dirk Schreckmann