Paul Williams
Paul Williams

Reputation: 1598

Math error during creation of countdown timer

I made a roughshod version of a countdown that has a resolution of 10ths of a second. I'm trying to express the result as 0:59. However, during the time the counter is at 450 tenths of a second (or 45 seconds), I noticed that the math below is returning as 1:45.

I switched the line of intMinutesRemaining = intQuestionTimer / 600 to have a \, with fixes the error... but now when the clock is trying to read 1:00, it will tick down to 0:60 then 0:59. This subtraction is being controlled by a timer which has an interval of 100 milliseconds.

(intQuestionTimer will be equal to say 600 for a 60 second timer and then countdown from there with a Timer tick causing it to be deducted by 1.)

Private Sub UpdateQuestionTimer()
    'lblQuestionTimer.Text = intQuestionTimer.ToString
    Dim strFormat As String

    Dim intMinutesRemaining As Integer
    Dim intSecondsRemaining As Integer

    intMinutesRemaining = intQuestionTimer / 600
    intSecondsRemaining = intQuestionTimer Mod 600

    strFormat = "{0:0}:{1:00}"

    lblQuestionTimer.Text = String.Format(strFormat, intMinutesRemaining, intSecondsRemaining / 10)

End Sub

What change should I make to have this consistently display the correct formatted text?

Upvotes: 1

Views: 41

Answers (2)

Steve
Steve

Reputation: 216303

You don't use the correct operator. You should use the \ operator also when showing the 10ths of seconds

Private Sub UpdateQuestionTimer()
    'lblQuestionTimer.Text = intQuestionTimer.ToString
    Dim strFormat As String

    Dim intMinutesRemaining As Integer
    Dim intSecondsRemaining As Integer

    intMinutesRemaining = intQuestionTimer \ 600
    intSecondsRemaining = intQuestionTimer Mod 600

    strFormat = "{0:0}:{1:00}"

    lblQuestionTimer.Text = String.Format(strFormat, 
    intMinutesRemaining, intSecondsRemaining \ 10)

End Sub

The operator / is used for floating point operations, but when your intQuestionTimer value is 599 dividing it by 10 produces 59,9. That value is rounded up to 60 again. Instead using the \ operator for integer operation the previous division yields 59 without the decimal part and it is displayed correctly.

Upvotes: 1

Mike Hofer
Mike Hofer

Reputation: 17022

This sounds like a rounding issue. Both variables are defined as integers. However, you're using the / floating point division operator, so that the result of the operation is rounded up and stored in the integer variable.

Use the integer division operator \, instead, or Math.Floor.

Upvotes: 1

Related Questions