[英]How to neglect value after 0 in decimal place VB.net?
我將小數變量四舍五入到4位。
Dim a As Decimal = Math.Round(b, 4, MidpointRounding.AwayFromZero)
如果值是5400.40019
,我將得到5400.4002
。 但是我不希望小數點后0
后面的值。 例如,當值為5400.4001
,我只需要5400.4000
。 如果值為5400.0412
, 5400.0000
需要5400.0000
。
我怎樣才能?
我不確定沒有字符串操作是否可以實現。 這應該為您提供所需的結果。 它將小數點四舍五入到小數點后四位,將其轉換為字符串,然后迭代字符串的每個字符以搜索小數位,然后搜索小數點后的第一個零。
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)
試試這個方法
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
您只需要在輸入十進制值時調用此方法即可。
例如
Dim b As Decimal = 5400.40019
MessageBox.Show("done" + CustomFormater(b).ToString())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.