-3

If I am getting a random double, how to get only the int? Examples:

1) 114.999 - get the "114" as an int

2) 565.343234 - get the "565" as an int.

  • Just cast it: `(int)114.999` etc. - this will truncate the number to the integer part, i.e. 14.999 -> 14, -14.999 -> -14. – Thomas Nov 16 '18 at 13:53
  • Thank you! what if the value is Double and not double? –  Nov 16 '18 at 13:54
  • 3
    "what if the value is Double and not double"? Then there's the method `intValue()` (or the possibility of unboxing before casting which basically would be `(int)d.doubleValue()` so `intValue()` would be easier). Of course there would be the issue of a `Double` potentially being null, so you'd have to handle that case and use a default value then (because primitives can't be null). – Thomas Nov 16 '18 at 13:55
  • Possible duplicate of [Converting double to int](https://stackoverflow.com/questions/21506465/converting-double-to-int) – cgrim Nov 16 '18 at 15:08

3 Answers3

1

Given the value :

float f = 114.999f;
int i = (int) f;

use a cast to downcast it to an int.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
1

The simplest way would be to cast your double value to an int. For example,

(int) 114.9999 == 114

However, the double type can represent numbers beyond the range of an int. You may need to check if your double is below the smallest possible integer or beyond the largest possible integer to avoid integer overflow issues.

Billy the Kid
  • 271
  • 2
  • 12
1

The easiest way to get the integer part of a floating point number would be a simple cast:

double d = 14.999;
int i = (int)d; //14

If you have a primitive wrapper like Double you can use the method intValue() that all subclasses of Number need to provide. However, since those are objects the references can be null and that has to be handled:

Double d = 14.999; //this makes use of auto-boxing
int i = d != null ? d.intValue() : 0; //here 0 is the default value if d is null

Note that this will just truncate the value which can lead to unexpected results due to precision issues, especially when calculations are involved. Due to that you could end up with a number like 14.999999999 when you'd expect 15 or something higher.

Another issue might be that you won't get the next smaller integer for negative values but the next higher, i.e. -14.999 will be truncated to -14.

You should keep that in mind and if those are issues for you have a look at the functions provided by the classes Math, BigDecimal etc.

Thomas
  • 87,414
  • 12
  • 119
  • 157