Setting the Decimal to format ##.## in java
I am trying to build a map with time starting from 06.00 to 23:59 as keys and I will keep track of a number for each time as value.I need the time to stored HH.mm as format and I am planning to build the map using a loop by incrementing one minute and run the following code inside the loop.The problem here is since I have to set the format as HH.MM strictly I have to get the input as String and format it and then parse it back as double which affects the perfomance.Is there a global setting to change so that whatever double number I choose in this particular class should be of the format ##.##.Also point here to note is since it is time it ends at 60 minutes and hence I have to break the current iteration with the help of .6.
Map map = new LinkedHashMap();
//Edit:Moved DecimalFormat Outside the loop
DecimalFormat df = new DecimalFor开发者_JAVA百科mat("##.##");
for (double time= 06.00; time<= 22.00; time= time+ 01.00)
{
String timeString = df.format(appointmentTime);
time = Double.parseDouble(timeString);
if (timeString.indexOf(".6") != -1)
{
time= time+ 00.40;
}
map.put(time,"<number>");
}
I beliI believe you choose the most complicated approach. Instead of iterating the time variable you could iterate a simple number indicating the minutes since 0 o’clock and then generate your time double only for the map.
for(int totalMinutes = 6 * 60; totalMinutes <= 22 * 60; totalMinutes ++) {
map.put(buildTimeDouble(totalMinutes),”<number>”);
}
But I believe (I do not understand your question in that point), it would be better not to use a double for the map key, instead you could use your own Time class, something like:
Time{
private int hour;
private int minutes;
public Time(int hour; int minutes) {
this.hour = hour;
this.minutes = minutes;
}
public toString(){
return hour + “:” + minutes
}
public static Time fromTotalMinutes(int totalMinutesSinceZeroOclock){
return new Time(totalMinutesSinceZeroOclock / 60; totalMinutesSinceZeroOclock / 60);
}
}
If you are worried about performance, one modification you should make to your code is to construct the DecimalFormat
just once, outside of the loop. The same instance can be reused over and over again inside the loop.
It's not a good approach to pre compute for all these values.Perhaps you can use a LRU cache.This can be easily implemented using a LinkedHashMap.I also think that you should not be using a double to represent time.Go through this article,it might give you some new ideas.
You should not work with doubles as counters, as rounding errors will creep in giving off-by-one errors.
Instead have an integer counter from which you calculate the times you need.
精彩评论