Home > database >  Convert numbers to hours
Convert numbers to hours

Time:09-23

I'm trying to do simple "total worked hours" calculator.

I have a textbox that I want to write in, say, 1.30, which would be 1 hour and 30 minutes. I have another textbox where I would put the same 1.30, and then I want to a label to add them and show 3 hours.

However, I can't find the right code to convert numbers to hours, and instead it shows 2.6. How can I make it show 3 hours?

Here is my code

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Label1.Text = Val(TextBox1.Text)   Val(TextBox2.Text)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        TextBox1.Text = My.Settings.SaveTextBox()
    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        My.Settings.SaveTextBox = TextBox1.Text()
    End Sub
End Class

CodePudding user response:

Using a NumericUpDown will save you having to check if the user really entered a number in a text box. Set the NumericUpDownMinutes to a maximum of 59 in the properties window. The PadLeft adds a leading zero to single digit minutes.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Hours = NumericUpDownHours.Value.ToString
    Dim Minutes = NumericUpDownMinutes.Value.ToString
    lblTotal.Text = $"{Hours}.{Minutes.PadLeft(2, "0"c)}"
End Sub

To get rounded hours

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim Hours = NumericUpDownHours.Value
    Dim Minutes = NumericUpDownMinutes.Value
    Dim RoundedHours = CInt(Hours   Minutes / 60)
    lblRoundedTotal.Text = RoundedHours.ToString
End Sub
  • Related