Tell me how to convert double to int ?
4 answers
The conversion itself is not complicated:
double doubleValue = 0.0001; int value = (int) doubleValue; Those. The instruction in general form looks like this:
type v1 = (type) v2; But here, there are pitfalls , namely - the type int contains values in the range from -2147483648 to 2147483647 , while they are integer, i.e. without fractional part. A double contains numbers ranging from 4.9E-324 to 4.9E-324 . Those. during conversion, overflow and / or disregarding the fractional part may occur.
For a more flexible conversion, use the BigDecimal and BigInteger classes.
If you want to round up or down, use Math.round ()
double a = 1.8; int b = Math.round(a); // b = 2 Double mDouble = 0.25; int mInt = (int)mDouble; Rounded in the right direction.
double dx = 10.787901; double newDouble2 = new BigDecimal(dx).setScale(3, RoundingMode.HALF_EVEN).doubleValue(); int ix = (int)newDouble2; // переводим в int UP - rounding towards a higher number for positive numbers and a smaller number for negative ones.DOWN - rounding to a smaller number for positive numbers and more for negative ones.CEILING - rounding to the larger side for both positive and negative numbers.FLOOR - rounding in the direction of smaller and for positive, and for negative numbers.HALF_UP - rounding up in the case of a number of 0.5HALF_DOWN - rounding down in the case of a number of the form 0.5HALF_EVEN - classic rounding
Link to documentation >>>