converting from long to float or double keeping the numbers after decimal
The below code outputs 0.0 instead of something like 0.17
Date startDate = new Date();
Date endDate = new Date();
double totalTime = (endDate.getTime() - startDate.getTime()) / 3600000;
System.out.println("Total Time: " + totalTime);
How can I modify so this will output a couple numbers after the decimal point.
Thanks,
John
> The below code outputs 0.0 instead of something like 0.17
That is because you are using long arithmetic.
> double totalTime = (endDate.getTime() -
> e() - startDate.getTime()) / 3600000;
>System.out.println("Total Time: " + totalTime);
>
> How can I modify so this will output a couple numbers digits
> after the decimal point.
Use double arithmetic.
Trydouble totalTime = (endDate.getTime() - e() - startDate.getTime()) / 3600000.0;
This is an integer type:
(endDate.getTime() - startDate.getTime())
as is this:
3600000
So when you divide them, the result is an integer type, meaning it drops the value after the decimal. You then assign it to a double, but there's still no decimal value. If you cast either the numerator or denominator to a floating point type, the result will be a floating point type.
double totalTime = (double)(endDate.getTime() - startDate.getTime()) / 3600000;
Two things:
- you're performing an integer division: everything between 0.0 and 0.9999... will be rounded of to zero. Try dividing with 3600000.0 instead of 3600000;
- if you're initializing startDate and endDate right after each other, you'll end up with 0.0 (unless you have a very ancient computer).
Try this:
import java.util.*;
import java.text.*;
public class SubtractDates {
public static void main(String[] argv) throws Exception {
StringdecPattern= "##########.00########";
DecimalFormat decFormat= new DecimalFormat(decPattern);
Date startDate = new Date();
double start = startDate.getTime();
System.out.println("Start Time: "+decFormat.format(start / 3600000));
Thread.sleep(1000);
Date endDate = new Date();
double end = endDate.getTime();
System.out.println("EndTime: "+decFormat.format(end / 3600000));
double totalTime = (end - start) / 3600000;
System.out.println("Total Time: "+decFormat.format(totalTime));
}
}
Message was edited by:
abillconsl