简体   繁体   中英

How do I turn decimals into integers? (Java)

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!

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 .

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM