简体   繁体   中英

Removing a decimal point in java

I am wanting to store an integer named Amount, I want it to be stored in pence so if the user entered 11.45 it would be stored as 1145. What is the best way to remove the decimal point? Should I be using decimalFormatting in Java?

Edit:

It is entered in string format, was going to covert it to an int. I will give one of your solutions ago and let you know if it works but not sure which one would be the best.. Thanks everyone.

times it by 100 and cast as int. Use decimal formatting is double / float are too inaccurate which they may be for money

If the user input is in the form of a string (and the format has been verified), then you can strip out the decimal point and interpret the result as an integer (or leave it as a string without the decimal point).

String input = "11.45";
String stripped = input.replace(".", ""); // becomes "1145"
int value = Integer.parseInt(stripped);

If it's a float already, then just multiply by 100 and cast, as @user1281385 suggests.

Tested and works . Even if the user enters a number without a decimal, it will keep it as such.

double x = 11.45; // number inputted

String s = String.valueOf(x); // String value of the number inputted
int index = s.indexOf("."); // find where the decimal is located

int amount = (int)x; // intialize it to be the number inputted, in case its an int

if (amount != x) // if the number inputted isn't an int (contains decimal)
    // multiply it by 10 ^ (the number of digits after the decimal place)
    amount = (int)(x * Math.pow(10,(s.length() - 1 - index)));

System.out.print(amount); // output is 1145

// if x was 11.4500, the output is 1145 as well
// if x was 114500, the output is 114500

What about convert to float, multiply by 100 and then convert to int?

String pound = "10.45"; // user-entered string
int pence = (int)Math.round(Float.parseFloat(pound) * 100);

This might be also useful: Best way to parseDouble with comma as decimal separator?

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