Reputation: 242
I have a double value I want to convert it to an integer value. However, the double value is large enough so that it causes problems. Here is an example:
double val1 = 74.1234567890
int val2;
I want the value of val2 to be equal to 741234567890
that is without decimal point. Does anyone have any suggestions on how to accomplish this?
Upvotes: 0
Views: 283
Reputation: 153957
And what do you want from 74.1234560000
. If it's always 10 digits, val * 1e10
, then conversion to a suitably large integral type, does the job. Otherwise, you'll have to define more clearly what you want. If it is based on the string used to initialize the double
, there it can't be done; many different strings can result in exactly the same internal value, including strings that would represent different values if interpreted as a real. At the other extreme, if you want the smallest integer value such that the value, multiplied by some negative power of 10, is exactly the value of the float... most floating point values will require something like 52 decimal digits, and the results almost certainly won't fit on any native integral type.
Upvotes: 2
Reputation: 19790
first of all, int can only holds values between −2,147,483,648 and 2,147,483,647. So 741234567890 is not going to fit. You will need a long for that (See @Daniel Fischer)
You can do just for the sake of an example:
//silly conversion
double val1 = 74.1234567890;
long val2 = Math.round(val1 * 10000000000);
If you want to support other values and want sort of an '.' remover, you should look at using Strings for this.
Upvotes: 0
Reputation: 12587
one thing you can do in Java is to parse it into a string, then take away the dot, and after that parse it into int.
double val1 = 74.1234567890;
String str = String.parse(val1);
str = str.replace(".", "");
int val2 = Integer.parse(str);
just remember that a conversion like yours will cause an overflow since double holds 2 words (8 bytes) and int only 2 (4 bytes)
Upvotes: 0