我想在我的文本框输出中只有 5 个有效数字。我可以知道什么 VB 函数可以做到这一点。谢谢
问问题
2378 次
3 回答
1
使用验证事件重新格式化输入的数字。您需要使用 ErrorProvider 向用户报告输入错误。
要获得固定数量的有效数字,您需要根据输入的值动态创建数字的格式化字符串。您可以使用 Math.Log10() 计算分数中所需的位数。像这样:
Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
Dim value As Double
If Not Double.TryParse(TextBox1.Text, value) Then
ErrorProvider1.SetError(TextBox1, "Please enter a valid number")
TextBox1.SelectAll()
Else
ErrorProvider1.SetError(TextBox1, "")
Dim intDigits As Integer = 0
If value <> 0 Then intDigits = CInt(Math.Truncate(Math.Log10(Math.Abs(value))))
If intDigits >= 0 Then intDigits += 1
Dim fracDigits = 5 - intDigits
If fracDigits < 0 Then fracDigits = 0
Dim format = "F" + fracDigits.ToString()
TextBox1.Text = value.ToString(format)
End If
End Sub
于 2012-12-25T18:00:43.347 回答
1
我发现该math.round
函数仅对数字的小数部分进行四舍五入。我想出的方法获取实数的整数部分,将其转换为小数并确定 10 的幂。
数字的小数部分除以 10 的相同幂并添加到转换为小数的整数部分。然后,您可以将该数字四舍五入并乘以上面找到的 10 的幂,以将任何实数四舍五入为所需的有效数字。我在表单中添加了一个按钮来测试功能,如下所示:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim x As Double = InputBox("input a real to round", , , , )
Dim y As Double
Dim sfs As Integer = InputBox("input sig figs", , , , )
y = fSigFig(x, sfs)
Console.WriteLine(y)
End Sub
'this function converts a real number with no formatting to a real number with a specified number of significant figures
Public Function fSigFig(ByVal areal As Double, ByVal sigfigs As Integer) As Double
Dim itens As Integer = 0
Dim intportion As Double = Int(areal) 'this is the integer portion of the number
Dim decportion As Double = areal - intportion 'this is the fractional portion of the number
If intportion < 1 Then 'areal only consists of a fractional portion, round directly
fSigFig = Math.Round(areal, sigfigs, MidpointRounding.AwayFromZero)
Else 'convert integer portion of number to a fraction and determine power of 10 required
While intportion >= 1
itens += 1
intportion /= 10
End While
'add the integer portion and decimal portion back together as a fraction number divided by 10^itens
'then round to specified significant figures and multiply by 10^itens
decportion /= 10 ^ itens
Dim numbertoround As Double = intportion + decportion
fSigFig = (10 ^ itens) * Math.Round(numbertoround, sigfigs, MidpointRounding.AwayFromZero)
End If
End Function
于 2016-09-18T20:37:43.280 回答
0
首先,谢谢大家,圣诞快乐。我会将 Hans Passant 的回复标记为 am answer
在问这个问题之前我确实想过。我问这个问题不是想找人为我做这个程序。(但我真的很感谢 Hans Passant)。我希望有一个内置函数,它可能被称为 ROUNDTO。我发布了这个问题,因为我想知道该函数是否存在的名称。
对于我的应用程序,我这样做了
Function roundTo(ByVal num As Double) As Double
If num >= 10000 Then
Return Math.Round(num)
Else
Dim tempnum = num
Dim counter = 0
Do
tempnum = tempnum * 10
counter = counter + 1
Loop While tempnum / 10000 < 1
Return Math.Round(num * 10 ^ (counter)) / (10 ^ (counter))
End If
End Function
于 2012-12-25T21:31:43.293 回答