How to convert a decimal to a long in C#

1 Answer

0 votes
using System;

/*
    ============================================================
    Convert a decimal to a long in C#.

    This program demonstrates:
      • Safe conversion using Convert.ToInt64()
      • Direct casting when the value is known to be in range
      • A helper function that performs the conversion and
        explains what happens internally.

    Notes:
      • decimal → long conversion requires the value to be within
        the range of Int64.
      • Convert.ToInt64() rounds to the nearest integer.
      • A direct cast (long)decimalValue truncates toward zero.
    ============================================================
*/

class DecimalToLongProgram
{
    // Converts a decimal to a long using the built‑in Convert class.
    // This method rounds the decimal to the nearest whole number.
    static long ConvertDecimalToLong(decimal value)
    {
        return Convert.ToInt64(value);
    }

    // Converts a decimal to a long using a direct cast.
    // This method truncates the decimal toward zero.
    static long CastDecimalToLong(decimal value)
    {
        return (long)value;
    }

    // Prints both conversion styles for comparison.
    static void ShowConversions(decimal value)
    {
        Console.WriteLine("Input decimal: " + value);

        long rounded = ConvertDecimalToLong(value);
        long truncated = CastDecimalToLong(value);

        Console.WriteLine("Rounded (Convert.ToInt64): " + rounded);
        Console.WriteLine("Truncated (cast to long): " + truncated);
        Console.WriteLine();
    }

    static void Main()
    {
        // Example values to demonstrate behavior
        ShowConversions(12.7m);
        ShowConversions(12.3m);
        ShowConversions(-5.8m);
        ShowConversions(42m);   // already an integer
    }
}


/*
run:

Input decimal: 12.7
Rounded (Convert.ToInt64): 13
Truncated (cast to long): 12

Input decimal: 12.3
Rounded (Convert.ToInt64): 12
Truncated (cast to long): 12

Input decimal: -5.8
Rounded (Convert.ToInt64): -6
Truncated (cast to long): -5

Input decimal: 42
Rounded (Convert.ToInt64): 42
Truncated (cast to long): 42

*/

 



answered Aug 6 by avibootz
edited Aug 6 by avibootz
...