Converting Strings for Mathematical Calculations

Hey All,

I’m new to .NET and converting and I’m hoping someone can help me make sense of the proper way to convert strings to other values. Specifically, here is a situation I’m facing:

I’m returning two values from a datasource as strings. One values is a representation of a span of time, and another is a count of how many attempts to access a system took place within the span of time.

Given these parameters (for example):

Span of time: 00:01:00
Attempts: 13

I’d like to calculate a third value that shows how many seconds each attempt to connect took place during that span of time. This involves converting the time span to seconds and then dividing by attempts. Where I am getting lost is with the conversion of types. I know the span of time needs to be converted to a date, reduced to seconds, then converted to a number to be divided by the attempts field, also converted to a number.

I’ve been playing around with code segments like this all morning to no avail:

Dim thisTime As String = "00:01:00"
Dim thisAttempts As String = "13"

Label1.Text = thisTime
Label2.Text = thisAttempts

Label3.Text = Math.Round(Integer.Parse(Convert.ToDateTime(Label1.Text)) / Integer.Parse(Label2.Text), 2)

If anyone could help me out, or point me in the right direction, I would appreciate it. I feel like I’m spinning my wheels.

Thank you pufa. Your post helped alot. Using the TimeSpan class I have been able to get the correct result from my calculation.

By chance, do you know how I could appropiately format this result? Currently the calculation returns: 00:00:04.6153846. I’d like to strip any leading zeros and round up to the first whole number.

I think the “c” parameter in the ToString method is supposed to handle formatting to some extent, but when I try to use it I get the error: “No accessible ‘ToString’ accepts this number of arguments”.

You need to convert the time span string to a TimeSpan object.

Then… convert the attemps string to Integer (this part is ok in your code)

and finnally… divide the TimeSpan by the number of attemps
The result will be another time span the you can format for presentation.

TimeSpan time = TimeSpan.Parse(thisTime);
TimeSpan average = TimeSpan.FromTicks(time.Ticks / Int32.Parse(thisAttemps));

Label3.Text = average.ToString(“c”);