taymyinl taymyinl - 11 days ago 7
Vb.net Question

How to neglect value after 0 in decimal place VB.net?

I round up decimal variable to 4 places.

Dim a As Decimal = Math.Round(b, 4, MidpointRounding.AwayFromZero)


If value is
5400.40019
, I will get
5400.4002
.
But I don't want the value after
0
in decimal place.
For example, when the value is
5400.4001
, I only want
5400.4000
. If the value is
5400.0412
, all I want is
5400.0000
.

How can I?

Answer

Try this method

Public Function CustomFormater(b As Decimal) As Decimal
    Dim a As Decimal = Math.Round(b, 4, MidpointRounding.AwayFromZero)
    Dim pre As Int32 = Convert.ToInt32(a.ToString().Split(".")(1))
    Dim result As Int32 = If(pre Mod 1000 >= 500, pre + 1000 - pre Mod 1000, pre - pre Mod 1000)
    Dim output As Decimal = Math.Round(Convert.ToDecimal(a.ToString().Split(".")(0) + "." + result.ToString()), 4, MidpointRounding.AwayFromZero)
    Return output
End Function

you just need to call this method with you input decimal value.

For example

Dim b As Decimal = 5400.40019
MessageBox.Show("done" + CustomFormater(b).ToString())
Comments