Reputation: 1
I've made a calculator that calculates measurements of a circle. I am currently using this command to ask the player to enter the radius of the circle:
String br = JOptionPane.showInputDialog(null, "Enter The Radius" , "CircleHacker", JOptionPane.PLAIN_MESSAGE);
int bravo = Integer.parseInt(br);
It works for now but I had just realized that since it is integer based, it can't do decimals! Is there anything that I can do to modify what I have here to make it to where it can handle decimals? -thanks (I have only known java for 4 days now by the way so I am just a beginner) -thanks!
Upvotes: 1
Views: 1099
Reputation: 201439
For a calculator, you might use Double.parseDouble(String) with something similar to this -
double bravo = Double.parseDouble(br);
But you could support arbitrary precision by using a BigDecimal like so -
BigDecimal bravo = new BigDecimal(br);
If you want to lose the decimal precision, you can perform several kinds of rounding and they're documented at the same links I just provided. For example, BigDecimal#toBigInteger()
and (long) bravo
(which is a cast, not rounding; but has the same practical effect as a floor()
function).
Upvotes: 1
Reputation: 2440
Decimal numbers have the datatypes double
and float
in Java. Thus, you could re-write your code as:
String br = JOptionPane.showInputDialog(null, "Enter The Radius" , "CircleHacker", JOptionPane.PLAIN_MESSAGE);
double bravo = Double.parseDouble(br);
Double is a more precise (yet larger) data type; since memory is cheap, I recommend using double
and not float
.
Upvotes: 2
Reputation: 13751
What about this?
double bravo = Double.parseDouble(br);
Assuming the user enters something like 1.23
this should solve your issue.
Note that you could also use float
instead of double
, but double
has higher precision which might or might not be relevant in your usecase.
Also note that in some locales, different separators like commas are used, you might have to handle them separately, see https://stackoverflow.com/questions/4323599/best-way-to-parsedouble-with-comma-as-decimal-separator
Upvotes: 1