• Post Reply Bookmark Topic Watch Topic
  • New Topic

reading a double  RSS feed

 
Russell Wade
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Real beginner here. Started to experiment with some code. Originally had the values hardcoded into the program. Then I wanted to read the values in through the console. The following code compiles but does give the desired results.

public static void main(String [] args) throws IOException{
DataInputStream in = new DataInputStream(
System.in);
System.out.println("Enter beginning balance:");
ip_value = in.readDouble();
System.out.println(ip_value);
TestAccount account = new TestAccount();
NumberFormat dollarformat = NumberFormat.getCurrencyInstance();
System.out.println("beginning balance = " + dollarformat.format(ip_value));
2000 was entered.
results:
6.004549348750547E-67
beginning balance = $0.00
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look at the Java API for java.io.DataInputStream you'll see that it reads native java data as bytes. The "readDouble()" method indicates that it'll read the next eight bytes and interpret it as a double (based on the IEEE 754 spec). This is not what you want.
You want to read in the characters you type and convert that to a double. try this:

And as a defensive measure, you'll probably want to put the "parseDouble()" call inside of a try/catch block.
[ March 08, 2004: Message edited by: Wayne L Johnson ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!