Reputation: 295
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?
Upvotes: 0
Views: 147
Reputation: 575
I'm not sure that this is achievable without string manipulation. This should give you the result you are looking for. It rounds the decimal to 4 decimal places, converts it to a string then iterates each character of the string searching for the decimal place and then the first zero after the decimal place.
Dim b As Decimal = 5400.40019D
Dim a As Decimal = Math.Round(b, 4, MidpointRounding.AwayFromZero)
Dim s As String = a.ToString
Dim s2 As String = ""
Dim bDecimalPointFound As Boolean
Dim bZeroFound As Boolean
For i As Int32 = 0 To s.Length - 1
Dim sChar As String = s.Substring(i, 1)
If bDecimalPointFound = True Then
If sChar = "0" Then bZeroFound = True
s2 &= If(bZeroFound = True, "0", sChar)
Else
s2 &= sChar
bDecimalPointFound = (sChar = ".")
End If
Next
Dim c As Decimal = Convert.ToDecimal(s2)
Upvotes: 1
Reputation: 310
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())
Upvotes: 0