How to Convert "TimeSpan" Into a "Float"

The Microsoft .Net framework allows you to quickly build powerful applications. You can use the pre-built .Net language features to solve many common programming tasks. For example, if you need to work with time, you can use the "TimeSpan" class, which represents an interval of time. The "TimeSpan" class stores a time value as a series of integer numbers that each store hours, minutes, seconds or milliseconds. You may find it more convenient to store the data as a floating point number. For example, you can convert "TimeSpan" into a floating point number with the format "seconds.milliseconds."

Things You'll Need

  • Visual Studio 2010
Show More

Instructions

    • 1

      Open Visual Studio 2010 by clicking on its program icon. When it loads, select "File/New/Project" and click "Visual C#/Console Application." A new Console Application project is created, and a blank page of source code appears in the main text editor window. The source code file has an empty main function.

    • 2

      Create a new "TimeSpan" object and give it a value of 125,000 ticks. Each tick represents a 100 nano-second time span. Write the following within the curly brackets of the main function:

      TimeSpan elapsedTime = new TimeSpan(125000);

    • 3

      Declare a "float" data type and name it "floatTimeSpan" by writing the following line of code:

      float floatTimeSpan;

    • 4

      Declare two "int" data types named "seconds" and "milliseconds," by placing the following line after the "float" declaration statement:

      int seconds, milliseconds;

    • 5

      Set the "seconds" variable equal to the "TimeSpan.Seconds" data value. You can do this by writing the following line of code right below the "int" declarations:

      seconds = elapsedTime.Seconds;

    • 6

      Set the "milliseconds" variable equal to the "TimeSpan.Milliseconds" data value. Place the following statement after the one written in the previous step:

      milliseconds = elapsedTime.Milliseconds;

    • 7

      Convert the "seconds" and "milliseconds" to a "float." You can do this by adding the value of "seconds" to the value of "milliseconds" divided by 1000. This is because there are 1000 milliseconds in a second. Write the following statement below the line written in the previous step:

      floatTimeSpan = (float)seconds + ((float)milliseconds / 1000);

    • 8

      Print out the "floatTimeSpan" value by writing the following statement:

      Console.WriteLine("Time Span: {0}", floatTimeSpan);

    • 9

      Execute the program by clicking the green "Play" button, which is situated at the top of the IDE. The program converts the "TimeSpan" into a "float" and prints out its value. The program output looks like this:

      Time Span: 0.012

Related Searches:

References

Comments

Related Ads

Featured