我将十进制变量向上舍入到4位。
Dim a As Decimal = Math.Round(b, 4, MidpointRounding.AwayFromZero)
如果值为5400.40019
,我将获得5400.4002
。
但我不希望0
之后的值为小数位。
例如,当值为5400.4001
时,我只想要5400.4000
。如果值为5400.0412
,我想要的只是5400.0000
。
我该怎么办?
答案 0 :(得分:1)
我不确定这是否可以在没有字符串操作的情况下实现。这应该会给你你想要的结果。它将小数舍入为4位小数,将其转换为字符串,然后迭代字符串的每个字符,搜索小数位,然后是小数位后的第一个零。
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)
答案 1 :(得分:0)
尝试此方法
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())