Make a float display 10:07 instead of 10.7

Hi

I am working on a timer for my game and I want to add some extra details to it. Right now I am simply using currentLevelTime.ToString("F2); and this kinda works. But there are a few things I don’t like about it.
Firstly, when separating the whole number and decimals there’s only a dot. I want it to be a colon instead.
Secondly, when it shows, for example, 10.7. I would like it to always show two digits on the decimals. Like 10:07. The same with the whole number. Instead of showing 8.1 it should show 08:01. How can I accomplish something like this?

Hi,

You need to split your number in two Strings: one with “10” and the over one with “7”.

Then count the length of the first part (let’s call it string1), if the lenght is = 1 (or not 2), this means you have to add a 0 at the beginning.

if (string1.Length < 2) 
   string1 = "0" + string1;

Same thing for the second string.

At the end of the day, you will want to display something like:

 timerText.text = string1 + ":" + string2;

Hey there

I’m guessing you want to split your time into minutes and seconds, then format it in a nice string. On that basis, here’s some example code to:

  • Split a floating point number of seconds into minutes and remaining seconds

  • Make use of the .net formatting system to convert those to different strings

             float total_seconds = 193.3f;
    
             //calculate the number of whole minutes, then subtract from total to get remaining seconds
             float minutes = Mathf.Floor(total_seconds / 60.0f);
             float seconds = total_seconds - minutes * 60.0f;
    
             //(A) gives 3:13.30
             //the minute is at least 1 integer digits (will show a 0 otherwise)
             //the seconds will be at least 2 integer digits (padded with 0s), 
             //and EXACTLY 2 fractional digits (padded with 0s)
             Debug.Log(string.Format("{0:0}:{1:00.00}", minutes, seconds));
    
             //(B) gives 03:13.30
             //same as (A), but minutes must be at least 2 integer digits
             Debug.Log(string.Format("{0:00}:{1:00.00}", minutes, seconds));
      
             //gives 03:13
             //same as (B), but with no fractional digits for the seconds
             Debug.Log(string.Format("{0:00}:{1:00}", minutes, seconds)); 
    
             //gives 3:13.3
             //same as (A), but the '#' means we now do AT MOST 2 fractional digits
             Debug.Log(string.Format("{0:0}:{1:00.##}", minutes, seconds));
    

The string formatting in .net is really handy once you get the hang of it. Key documentation that’s useful is:

General string.Format documentation:

Custom numeric format documentation (can also be used in ToString functions):

-Chris