Truncate a Decimal Number to Some Fixed Decimal Places

One problem VB.NET developers usually face is how to truncate a decimal number to some specified number of digits after it without rounding off. The Math library doesn’t provide any method to do this. And almost all of the common functions that do similar job, round them off to specified number of digits instead of truncating them. e.g. The String.FormatNumber, String.Format, Math.Round etc. round off, and there doesn’t seem to be any native method to truncate it instead of rounding it off.

Fortunately, it’s easy to construct a function that does our job.

Function FixDecimal(ByVal number As Decimal, ByVal digits As Integer) As Decimal
    Dim x As Integer = 10 ^ digits
    Return Fix(number * x) / x
End Function

For ease of use, this may be declared a Public Shared member of class or as a Public member of a module, or maybe as an extension method, as the situation permits.


4 Responses to “Truncate a Decimal Number to Some Fixed Decimal Places”

  1. Selvi Says:


    This is really cool….solved my issue..Thank you !!!

  2. Bhavik Says:

    Hello sir plz help me in VB mathematics problem…

    Text3.Text = Text1.Text * Text2.Text / 10
    if i have the value of
    Text1.Text = 6.6
    Text2.Text = 66
    it takes
    Text3.Text = 43.56
    But i want only integer value not decimal
    just like that Text3.Text = 43
    i also use round function but it’s not giving me proper answer wich i want…
    it can add +1 value in last integer value if decimal value is 5 or more then 5…

  3. Wayne Says:

    Thank you Pradeep. This is a perfect solution for a project I was working on!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: