Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,596 questions

55,330 answers

573 users

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 1 day ago by avibootz
edited 1 day ago by avibootz
...