For a project at school, I have to make a java program to retrieve data from a database.
This is my code:
public class Tijdstip
public double testTijd(String tijdstip1)
// splitting the time
String tokens = tijdstip1.split("\\s+");
int hours = Integer.parseInt(tokens);
int minutes = Integer.parseInt(tokens);
//returning the time
double result = hours + ((double)minutes/100);
I fill in a time as string like: "7 10", meaning 7:10am and it must return a double like 7.10
But it returns 7.1, how do I make it so it will return 7.10 instead of 7.1?
You need to understand the difference between how a number is represented and how it is displayed. There is no numeric difference between 7.1 and 7.10; there is no way to make the number one instead of the other. You can display 7.1 as 7.10 using output formatting such as found in the Format class.
As a side issue: Storing this as a double would be a bad idea in a program of any size. There are many classes for representing time, and they all take into account the non-decimal nature of time divisions. Doubles don't do this.
The short answer is that you cannot do this if you must keep the result as a double. The double doesn't know anything about leading or trailing zeros. You can only do this when the result is formatted as a String. E.g.,
String.format("%.2f", 7.1) gives the string
"7.10". You can easily do this formatting every time you display the number, but you cannot make the number itself remember the extra zero.
When you return double it will always truncate your last number if it is zero. so make it a string and return
If you need double value which has only two digits after dicimal, you can try following:
double d = 1.164444; double r = Math.rint(d * 100)/100; System.out.println(r);