2

I get a double value (eg. -3.1234) which contains a value in decimals (0.1234 in this case). I want to remove the value in decimal value (in this case I wanted the value -3). How do I do it? I know how to remove the decimal if the decimal only has 0, but in this case I don't have the decimal value as 0.

Anyways here is the code for that:

DecimalFormat format = new DecimalFormat();
format.setDecimalSeparatorAlwaysShown(false);

Double asdf = 2.0;
Double asdf2 = 2.11;
Double asdf3 = 2000.11;
System.out.println( format.format(asdf) );
System.out.println( format.format(asdf2) );
System.out.println( format.format(asdf3) );
/*
prints-:
2
2.11
2000.11
*/
Dat Nguyen
  • 1,626
  • 22
  • 25

5 Answers5

4

If you just want to print it :

String val = String.format("%.0f", 2.11)
// val == "2"

If you want to keep the double type but without decimals :

double val = Math.floor(2.11);
// val == 2.000

If you don't care about type you can cast the double into int :

int val = (int) 2.11;
// val == 2

//double as object
int val = myDouble.integerValue();
Lionel Briand
  • 1,732
  • 2
  • 13
  • 21
1

You can simply use the intValue() method of Double to get the integer part.

Anuj
  • 1,912
  • 1
  • 12
  • 19
1

You can cast it to int

int i=(int)2.12
System.out.println(i); // Prints 2
Rasel
  • 5,488
  • 3
  • 30
  • 39
1

Round up decimal value & convert it into integer;

Integer intValue = Integer.valueOf((int) Math.round(doubleValue)));
priyanka kamthe
  • 519
  • 2
  • 5
  • 19
  • Wow, maybe you should add an "(int)" in front of Integer.valueOf, just to be sure... :) – Prexx May 29 '17 at 09:46
1

http://www.studytonight.com/java/type-casting-in-java check out type conversion in java

    double asdf2 = 2.11;
    int i = (int)asdf2;
    System.out.println(asdf2);
    System.out.println(i);

    Output:

    2.11`
    2