programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

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

crystal smith
Greenhorn
Posts: 10
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
• 1
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
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
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
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
Thank you