14

I just wants to convert from double to int in my UI i am rendering as a double but for the backend i want convert to integer.

Double d = 45.56;

OutPut = 4556;

Please can anybody tell me how to get the value in this format.

Anshuman Patnaik
  • 221
  • 1
  • 3
  • 9
  • For your information if you cast `Double` to `int` then the result it `45` not `4556` but if you really want output `4556` then remove `.(dot)` from your `Double` value. `what's wrong?` – M D Jul 23 '15 at 10:53
  • 2
    double d = 45.56; String temp = String.valueOf(d); if (temp .contains(".")) { temp = temp .replaceAll(".",""); } – Jigar Shekh Jul 23 '15 at 10:56

4 Answers4

38

Try this way, Courtesy

double d = 45.56;
int i = (int) d;

For better info you can visit converting double to integer in java

Community
  • 1
  • 1
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
15

If you just want to convert the Double to int,

Double D = 45.56;
int i = Integer.valueOf(D.intValue());
//here i becomes 45

But if you want to remove all decimal numbers and count the whole value,

//first convert the Double to String 
double D = 45.56;
String s = String.valueOf(D);
// remove all . (dots) from the String
String str = str.replace(".", "");
//Convert the string back to int
int i = Integer.parseInt(str);
// here i becomes 4556
Prokash Sarkar
  • 11,723
  • 1
  • 37
  • 50
2

You are using the Double as object(Wrapper for type double). You need to fist convert it in to string and then int.

Double d=4.5;
int  i = Integer.parseInt(d.toString());

If you want it in the Integer Object Wrapper then can be written as

Integer  i = Integer.parseInt(d.toString());

EDIT If you want to get the desired result - You can go like this-

    Double d = 4.5;
    double tempD = d;
    int tempI = (int) tempD * 100;
    //Integer i = tempI;
Sanjeet A
  • 5,171
  • 3
  • 23
  • 40
  • Oh, I couldn't guess the reason of down voting. Thanks @2Dee I will keep in mind. – Sanjeet A Jul 23 '15 at 13:01
  • 1
    I'm not sure about the downvote, that was not me (otherwise I would have downvoted other similar answers as well). I vote considering the ability of the post to answer the question, which you do ;) Thanks for keeping my remark in mind though, I'm sure you'll realize closing duplicates instead of answering them would increase the quality of the site dramatically, which is what we want ;) – 2Dee Jul 23 '15 at 13:06
1

try this code

double d = 45.56; 
String temp = String.valueOf(d); 
if (temp .contains(".")) { 
    temp = temp .replaceAll(".",""); 
}
// After if you want to convert to integer then
int output = Integer.parseInt(temp);
Jigar Shekh
  • 2,800
  • 6
  • 29
  • 54