views:

2700

answers:

2

I am sure this is very simple problem, but I am new to vb.net so am having an issue with it.

I have a Decimal variable and I need to split it into two seperate variables, one containing the integer part, and one containing the fractional part.

eg for x = 12.34 you would end up with a y = 12 and a z = 0.34

Are there any nice built in functions to do this or do I have to try and work it out manually.

Many thanks in advance

+6  A: 

You can use Math.Truncate(decimal) and then subtract that from the original. Be aware that that will give you a negative value for both parts if the input is decimal (e.g. -1.5 => -1, -.5)

EDIT: Here's a version of Eduardo's code which uses decimal throughout:

Sub SplitDecimal(ByVal number As Decimal, ByRef wholePart As Decimal, _
                 ByRef fractionalPart As Decimal)
    wholePart = Math.Truncate(number)
    fractionalPart = number - wholePart
End Sub
Jon Skeet
+1  A: 

Edit: (as Jon Skeet says) Beware that the integer part of a decimal can be greater than an integer, but this function will get you the idea.

    Sub SlipDecimal(ByVal Number As Decimal, ByRef IntegerPart As Integer, _
                    ByRef DecimalPart As Decimal)
        IntegerPart = Int(Number)
        DecimalPart = Number - IntegerPart
    End Sub

Use the Jon version if you are using big numbers.

Eduardo Molteni
Decimals can go way outside the range of Integers (and Longs)
Jon Skeet
Yes, but it just the idea
Eduardo Molteni