Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

working with doubles and strings  RSS feed

 
Glen Bland
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an assignment for my Java class complete with the exception that I get an occasional error with certain numbers.

I have the problem narrowed down to this:

I'm inputing a dollar amount as a string and casting it to double for amountDue.
I do the same for amountPaid.
I subtract the amountDue from the amountPaid.
cast the result back to a string, formatt it down to 2 decimal places and display it.
with some numbers this works perfectly, with others an exception is thrown.
Any idea why?
see code below..
note that this is a very small portion of the overall assignment.

static String calcChangeDue( String sAmountDue, String sAmountPaid ) throws IOException
{
double dAmountDue = Double.parseDouble( sAmountDue );
double dAmountPaid = Double.parseDouble( sAmountPaid );
double dChangeDue = ( dAmountPaid - dAmountDue );
String sChangeDue = ( "" + dChangeDue );
return sChangeDue;
}

The exception I get is:
Exception in thead "main" java.lang.NumberFormatException: For input string "649999999999999"
at java.lang.NumberFormatException.forInputString(Unknown Source)
(... at other things as well)

(note that the number givin is the value of the decimal place and is over 13 digits and double has a precisiion up to 12 significant digits)


[ October 16, 2006: Message edited by: Glen Bland ]
[ October 16, 2006: Message edited by: Glen Bland ]
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could either inform the user about the size of the number they can input, or you could use a class like java.math.BigDecimal.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!