-2

Possible Duplicate:
Java : how do I get the part after the decimal point?

In my previous post I didn't give proper explanation. This is my exact scenario.

I have a double variable d = 1.15.

I want the number after the decimal point, i.e. "15".

What is best way to achieve this in Java?

I have tried like this:

Double d = 1.15;
String str = d.toString();
int len = str.substring(str.indexOf(".")).length() - 1;
int i= (int) (d * (long)Math.pow(10,len) % (long)Math.pow(10,len));

But I didn't get the proper answer because when I convert d.toString() the answer is 14.999999999999986.

Community
  • 1
  • 1
user1023675
  • 289
  • 1
  • 4
  • 13
  • 4
    Instead of asking new question why not update the old one? There is a functionality to update your question on this site. – Harry Joy Jan 17 '12 at 06:43
  • 1
    Please don't post the same question twice. There is plenty of activity on your other question, including a correct answer (which you should accept). – Paul Jan 17 '12 at 06:53
  • 1
    You should edit your previous post if it's not clear. See Arjun's answer there, he got it right. – Paul Jan 17 '12 at 06:59
  • 1
    By the way, you **still** haven't explained what you really mean. An example is not an explanation. And "the number after the decimal" is nonsensical from a mathematical stand point. – Stephen C Jan 17 '12 at 07:03

2 Answers2

0

Instead of d.toString(), try this:

String str = String.format("%.2f", d);
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0
Double x = 1.2345;
Double p = x - Math.floor(x);
String[] sp = p.toString().split("\\.");

The sp[1] variable will now contain the string 2345, as long as there is in fact a decimal part to it. If there isn't, sp will only have one item in it, so you can check the length and do whatever you want to handle such a situation.

Polynomial
  • 27,674
  • 12
  • 80
  • 107