How to convert a decimal to a long in VB.NET

1 Answer

0 votes
Imports System

' ============================================================
' Convert a Decimal to a Long in VB.NET.
'
' This program demonstrates:
'   • Conversion using CLng(), which rounds to the nearest whole number.
'   • Conversion using a direct CType() cast, which truncates toward zero.
'   • A helper function that prints both results for comparison.
'
' Notes:
'   • Decimal → Long conversion requires the value to be within Int64 range.
'   • CLng() performs banker's rounding (to nearest even).
'   • CType(value, Long) truncates the fractional part.
' ============================================================

Module DecimalToLongProgram

    ' Converts a Decimal to a Long using CLng(), which rounds.
    Function ConvertDecimalToLong(value As Decimal) As Long
        Return CLng(value)
    End Function

    ' Converts a Decimal to a Long using CType(), which truncates.
    Function CastDecimalToLong(value As Decimal) As Long
        Return CType(value, Long)
    End Function

    ' Prints both conversion styles for comparison.
    Sub ShowConversions(value As Decimal)
        Console.WriteLine("Input decimal: " & value)

        Dim rounded As Long = ConvertDecimalToLong(value)
        Dim truncated As Long = CastDecimalToLong(value)

        Console.WriteLine("Rounded (CLng): " & rounded)
        Console.WriteLine("Truncated (CType): " & truncated)
        Console.WriteLine()
    End Sub

    Sub Main()
        ' Example values to demonstrate behavior
        ShowConversions(12.7D)
        ShowConversions(12.3D)
        ShowConversions(-5.8D)
        ShowConversions(42D)   ' already an integer
    End Sub

End Module


' run:
'
' Input decimal: 12.7
' Rounded (CLng): 13
' Truncated (CType): 12
'
' Input decimal: 12.3
' Rounded (CLng): 12
' Truncated (CType): 12
'
' Input decimal: -5.8
' Rounded (CLng): -6
' Truncated (CType): -5
'
' Input decimal: 42
' Rounded (CLng): 42
' Truncated (CType): 42
'

 



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