A. N. Other
A. N. Other

Reputation: 489

Android game, displaying only two decimals (only hundreds of seconds) for time spent in the game UI HUD

I am writing a simple Android game, and I would like my game UI HUD to display only two decimals (i.e only hundreds of seconds) for the time spent, time passing, and similar. One sample of my code is this:

canvas.drawText("Fastest: " + formatTime(fastestTime) + " S", 10, 20, paint);

formatTime returns time with milliseconds. (I.e. 54.335 S). This is useless for my needs. I tried DecimalFormat, as suggested in other questions before, without success. I suspect the problem is with canvas.drawText and not "simply" System.out.println()

Any help much appreciated.

Upvotes: 0

Views: 92

Answers (1)

Marco Zielbauer
Marco Zielbauer

Reputation: 525

I want to propose two different methods to reach your goal:

1. drawText()

Looking at the documentation of Canvas it looks like there is a method that also takes in the first and last index of the String to draw.

drawText(CharSequence text, int start, int end, float x, float y, Paint paint)

Draw the specified range of text, specified by start/end, with its origin at (x,y), in the specified Paint.

I suggest changing your code to this:

canvas.drawText("Fastest: " + formatTime(fastestTime) + " S", 0, 7, 10, 20, paint);

start: 0, end: 7 (as "54.33 S" also includes the dot).

A possible issue is if the seconds are less than 10 or bigger than 100 (which affect the length of the String and therefore the end index).

  1. If the "formatTime()" method returns a String, you can get the index of the '.' and add 2 to add the milliseconds.
  2. If the "formatTime()" method returns a rounded double, you have to convert the double to a String and apply step 1.

The drawText() call will now look like this:

String time = formatTime(fastestTime);
int endIndex = time.indexOf('.') + 5;
canvas.drawText("Fastest: " + formatTime(fastestTime) + " S", 0, endIndex, 10, 20, paint);  

2. Crop the String

If my first solution does not work (I have not tried it) you can simply crop the String to the milliseconds and draw the whole String.

I assume that the format time returns a String (if not convert it to a String and proceed).

String time = formatTime(fastestTime);
int endIndex = time.indexOf('.') + 3; //the endIndex of String.substring() is exclusive.

canvas.drawText("Fastest: " + time.substring(0, endIndex) + " S", 10, 20, paint);

Upvotes: 2

Related Questions