How do use the % operator?

Under a similar note to my other question at http://answers.unity3d.com/questions/18765/how-do-i-format-a-string-into-daysminuteshoursseconds I'd like to know how excatly I should use the % operator.

I need to calculate days,hours,minutes and seconds. So far I have..

displaySeconds= seconds % 60;
displayMinutes =seconds /60; 

..but I got this from an example and I've no idea what th % is doing or how to go from here to get days/hours.

Many thanks!

2 Answers

2
displaySeconds = seconds % 60; 

This shows you the "remainder" of seconds / 60

e.g.

120 seconds / 60 would be equal to 2 with 0 remainder

or

121 seconds / 60 would be equal to 2.01666667 or 2 and 1 remainder

What that script does is tell you how many seconds you should display on a clock i.e. if the time was 2 seconds you'd display 2 seconds, if the time was 62 seconds you'd display 2 seconds as well.

The minutes part of the script is pretty straight forward, there are 60 seconds in a minute...

EDIT:

Similarly for days and hours, if you know how many seconds there are in an hour (3,600) and how many seconds in a day (86,400) You can calculate those using the same formula.

e.g.

displaySeconds = seconds % 60;
displayMinutes = (seconds / 60) % 60;
displayHours = (seconds / 3600) % 24;
displayDays = seconds / 86400;

I went and did an example JS:

var displaySeconds : int;
var displayMinutes : int;
var displayHours : int;
var displayDays : int;
var seconds : float;

function Update () {
    seconds = Time.time;
    displaySeconds = seconds % 60;
    displayMinutes = (seconds / 60) % 60;
    displayHours = (seconds / 3600) % 24;
    displayDays = seconds / 86400;
}

function OnGUI(){
    GUI.Label(Rect(0,0,200,30),"Time " + displayDays + " : " + displayHours + " : " + displayMinutes + " : " +  displaySeconds);
}

This will display the time since the program started in Days : Hours : Minutes : Seconds

Just swap out Time.time for whatever system you want to have shown in your game (game-time probably)

var seconds : int = 12345;

displaySeconds = seconds % 60;
displayMinutes = seconds / 60;

It's very important the seconds variable to be int, otherwise the displayMinutes variable would receive a float value.

1/60 is still a decimal

–

you probably meant you should cast displayMinutes as an int

–

1/60 is cero (integer division) :P (i meant that the variable would receive a float value). As displayMinutes will surely be used in a format string like {0:00} then it's better it to be an integer for avoiding the cast. Using the float value directly in the format string will round the display value to the nearest integer.

–

int casting the exponent part of the real number is simply omitted i.e. rounded down which is exactly what you want and either method has no fewer castings if you were using Time.time I guess your method is fine too.

–