Dot Net Perls

Convert Miles to Kilometers - C#

by Sam Allen

Problem

You want to convert miles to kilometers, and kilometers to miles. The USA keeps miles but most other countries use the metric system. It is important for you to maintain compatibility with many cultures.

InputOutput
200 m321.9 km
321.9 km200 m
500 km310.7 m
310.7 m500 km

Solution: static conversion methods in C#

The solution consists of one static class and two methods in it. These methods are effective in converting from miles to kilometers and back again. They are in the public domain and are tested.

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("{0} = {1}",
            200,
            ConvertDistance.ConvertMilesToKilometers(200));

        Console.WriteLine("{0} = {1}",
            321.9,
            ConvertDistance.ConvertKilometersToMiles(321.9));

        Console.WriteLine("{0} = {1}",
            500,
            ConvertDistance.ConvertKilometersToMiles(500));

        Console.WriteLine("{0} = {1}",
            310.7,
            ConvertDistance.ConvertMilesToKilometers(310.7));
    }

    public static class ConvertDistance
    {
        public static double ConvertMilesToKilometers(double m)
        {
            return m * 1.609344;
        }

        public static double ConvertKilometersToMiles(double k)
        {
            return k * 0.621371192;
        }
    }
}

Information: how the methods are compiled

As I noted, the double type here is actually termed float64, meaning a 64-bit number. This snippet shows the ConvertKilometersToMiles method. You can see it uses the mul opcode to multiply.

.method public hidebysig static float64
    ConvertKilometersToMiles(float64 k) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldc.r8 0.621371192
    L_000a: mul 
    L_000b: ret
}

The ldrc.r8 opcode pushes the supplied value (the 0.621371192) onto the stack as a float. This helps us understand what is happening under the hood.

Information: output from the above methods

These methods are not really precise, but they are fairly accurate. Match up the numbers with the table at the start. To reproduce this output, simply paste the supplied code into a console program.

200 = 321.8688
321.9 = 200.0193867048
500 = 310.685596
310.7 = 500.0231808

Summary: converting units of distances

It is interesting the extent of the loss of precision. In chemistry, there is a concept of significant digits, and that concept certainly applies here as well.

We saw how the methods are converted into MSIL, and also saw how we can use a static class to store static methods more logically.

Dot Net Perls
About
Sitemap
Conversion
Convert Char Array to String
Convert List to Array
Convert Bytes to Megabytes
Convert Dictionary to String
Convert Degrees Celsius to Fahrenheit
New
GZIP Accept-Encoding Request
Convert bool to int
© 2008 Sam Allen. All rights reserved.