0

I want to turn any double value into an intenger. I know that the part behind the comma will be lost.

import java.lang.*;

public int doubleToIntenger(double dbl){
    int intenger;
    intenger = intenger.intValue(dbl);
    return intenger;
}

But I'm getting this error as a tooltip in my editor:

int cannot be dereferenced
1cedsoda
  • 623
  • 4
  • 16
  • What do you think `intenger` holds? What would be the value or reference that it is holding currently? what do you think `int intenger;` does? – SMA Feb 24 '18 at 14:50
  • Its just a simple declaration. Or did I misunderstand your question? – 1cedsoda Feb 24 '18 at 14:54
  • You may not call methods on primitive types. Importing java.lang.* is useless, too. – JB Nizet Feb 24 '18 at 14:55
  • Ok, thanks ;D I'm not very experienced in java. I have to find a way to convert an double into an intenger. This was my first idea. – 1cedsoda Feb 24 '18 at 14:58
  • Your first idea should be to google for "convert double to integer in Java". Note that it's spelt "integer", not "intenger". Trying random code is not an effective solution. – JB Nizet Feb 24 '18 at 14:58
  • The majority of Germans will spell it "integer"... – Ralf Kleberhoff Feb 24 '18 at 16:52
  • One more thing: avoid imports with asterisk - they are a maintenance risk, and there's no need at all to import anything from the `java.lang` package. – Ralf Kleberhoff Feb 24 '18 at 16:54

1 Answers1

0

Just cast double to int, if you only care about before fraction.
But be carefull

double x = 1.999999;
int val = (int)x;// val will be 1
miskender
  • 7,460
  • 1
  • 19
  • 23
  • Thanks, this works. I have already tried it with casting, but I got an error. Seems to be something else. – 1cedsoda Feb 24 '18 at 15:04
  • @phyyyl If the double value comes from a arithmetic operation, you have to think before casting it. Because 1.0 *2 does not have to be resulted as 2.0. It can be 1.99999998. Floating point arithmetic does not produce exact results. – miskender Feb 24 '18 at 15:07
  • So I should round the value first and than cast it? – 1cedsoda Feb 24 '18 at 15:08
  • @phyyyl Yes you can do that, but rounding 1,51 will result as 2. You can use epsilon arithmetic if you dont want that behavior. – miskender Feb 24 '18 at 15:11
  • I would round to the first decimal place after the comma. 1,51 -> 1,5 -> 1 ; 1,999 -> 2,0 -> 2 – 1cedsoda Feb 24 '18 at 15:21