• Post Reply Bookmark Topic Watch Topic
  • New Topic

storing input from the user as a string variable and then converting it to a double ?  RSS feed

 
crystal smith
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to make a program that calculates the change due in dollars and cents. The user inputs both the amount due and the amount tendered. My program only works with whole numbers any suggestions?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12564
49
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for money, using whole numbers is generally preferred. Doing calculations with floats will start leading to strange rounding errors.

The user will probably want to input a float, since it is more natural. That means you will have to convert the input from dollars and cents to just cents, work with that, and then convert it back for any output.

So the question would be what have you tried, and where are you stuck?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

If you have the input from the user in a string, then you can convert it to a double using a method in the class java.lang.Double. Have a look at the API documentation (<- click the link) and see if you can find the method that does it for you.
 
Robert D. Smith
Ranch Hand
Posts: 221
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't recall what I was working on, but I have found that BigDecimal works really well for most floating point needs. You might also want to take a look a Winston's guide on working with user input.

Regards,
Robert
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Big Decimal is rather more akin to fixed‑point arithmetic than floating‑point. There is an int[] which denominates the value as decimal numbers and an int which represents the location of the decimal point/number of digits after the decimal point. You can see some examples of how it works here. Getting a BigDecimal from a Scanner is really easy:-
 
crystal smith
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!