问题描述:

For a project at school, I have to make a java program to retrieve data from a database.

This is my code:

import java.text.*;

import java.util.*;

public class Tijdstip

{

public Tijdstip()

{

}

public double testTijd(String tijdstip1)

{

// splitting the time

String[] tokens = tijdstip1.split("\\s+");

int hours = Integer.parseInt(tokens[0]);

int minutes = Integer.parseInt(tokens[1]);

//returning the time

double result = hours + ((double)minutes/100);

return result;

}

}

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.

网友答案:

Try this

new DecimalFormat("#.00").format(result);
网友答案:

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);
相关阅读:
Top