Link to home
Start Free TrialLog in
Avatar of go4java
go4java

asked on

Java: Get part before and after decimal point

How to get the 2 parts from a double value: 3.141592654 ???

part1 = 3
part2 = 141592654
Avatar of Kuldeepchaturvedi
Kuldeepchaturvedi
Flag of United States of America image

conver the dobule to String and then do a indexOf ..

something like..

Double d = new Double(3.1415......);
String sd = d.toString();
int idx = sd.indexOf(".");
String part1 = sd.substring(0,idx);
String part2 = sd.subString(idx);
Double d = new Double(3.141592654);
long part1 = d.longValue();
long part2 = d.toString().substring(d.toString().indexOf('.'), d.toString().length());
Avatar of zzynx
What are part1 & part2?
String's, doubl's, long's??
ASKER CERTIFIED SOLUTION
Avatar of dberner9
dberner9
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
for strings:
String[] parts = new Double(d).toString().split("\\.");
String part1 = parts[0];
String part2 = parts[1];

for longs:
String[] parts = new Double(d).toString().split("\\.");
Long part1 = Long.parseLong(parts[0]);
Long part2 = Long.parseLong(parts[1]);
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
dberner9's code will work for JDK1.4 & above but its if you are using 1.4 then its the right way of doing it
Avatar of go4java
go4java

ASKER

will test on monday and come back to you. thanks so far :-)
>>double d = 3.141592654;
>>long integerPart = (long)d;
>>double decimalPart =  d - (double)integerPart;

intelligence solution, but
part2 (decimalPart) will contains ( . ) /*dot*/ at the front ..
>> part2 (decimalPart) will contains ( . ) /*dot*/ at the front ..

That is what is required? I guess you can also use:

long integerPart = ( long ) d ;
double decimalPart = d - integerPart ; // no need to type-cast
thanks