If I have:
int a = 123;
int b = 456;
How do I get?:
double c = 123.456;
If I have:
int a = 123;
int b = 456;
How do I get?:
double c = 123.456;
How about this:
int a = 123; int b = 456;
double c = Double.parseDouble(a + "." + b);
Mathematical solution
int a = 123;
int b = 456;
double c = a + (b == 0 ? 0 : b / Math.pow(10, 1 + (int) Math.log10(b)));
explanation:
1 + (int) Math.log10(b) // number of digits (3 in case of 123)
Math.pow(10, 1 + ... ) // 10...0 - 1 with required number of zeroes
Create strings out of each integer
, then concatenate the strings together, inserting a "." between the two. Then convert the resulting string
to a double
.
If you want to take a purely computational approach, as opposed to one involving conversion back and forth between string and numeric form, then you could do this:
double concatToDouble(int integer, int fraction) {
if (fraction < 0) {
throw new NumberFormatException("The fractional part must not be negative");
} else if (fraction == 0) {
return integer;
} else {
int numFractionDigits = (int) Math.log10(fraction) + 1;
int scaleFactor = (int) (Math.pow(10, numFractionDigits) + 0.1);
return (double) ((long) integer * scaleFactor
+ (long) Math.signum(integer) * fraction)
/ scaleFactor;
}
}
It's a little longer to express, but it will perform better because it involves a lot less work than the conversions to and from string format.
Computational notes:
double
you want, butdouble
has no exact representation for the decimal number you want to form.integer
to type long
before computing the scaled value, so as to avoid overflow.Math.signum()
returns 1.0 for arguments greater than 0, and -1.0 for arguments less than zero. This allows the method to handle negative values of integer
gracefully.Math.pow()
before truncating the result to an integer in case the result of pow()
, which isn't necessarily exact, is slightly smaller than the exact result.Do note, however, that the problem itself seems not to account for the (infinitely many) insignificant leading zeroes that notionally precede the significant digits of the fraction part. That is, without a third parameter indicating the scale of the fraction part, there is no way to get a result of 123.0456
, 123.00456
, etc..
If the size of b
is not aleatory, simply initialize a new wrapper:
new Double(a + ((double)b / 1000))
Note that I'm casting b
to double
explicitly here, in order to obtain a double
value of b / 1000
instead of an integer value.
If size of the ints shouldn't matter,
public class TestStackOverflowQuestion {
public static void main(String[] args) {
int a = 123;
int b = 456;
double c = a + Double.parseDouble("." + b);
System.out.println(c);
}
}