我的表单包含多个NumericUpDown
控件。这些控件显示不同的小数位数。
稍后在我的代码中,我将不同的NumericUpDown.Value
放在字符串数组arrStr()
中,如下所示:
arrStr(1) = NumericUpDown1.Value
arrStr(2) = NumericUpDown2.Value
arrStr(3) = NumericUpDown3.Value
然后我将带有File.WriteAllLines
函数的数组打印到文本文件中。
如果例如NumericUpDown1.Value = 1.00
,NumericUpDown2.Value = 2.30
和NumericUpDown3.Value = 2.124
,则该文件中包含以下值:
1
2.3
2.124
我想看看:
1.00
2.30
2.124
我尝试了Format
,但是格式化方法不方便,因为已经为每个NumericUpDown
设置了小数位数。再次完成这项工作会很烦人,但现在使用Format
。
答案 0 :(得分:1)
您可以使用String.Format
强制两位小数:
Dim value As Double = 2.3
Dim formatted = String.Format("{0:f2}", value) ' 2.30 '
Standard Numeric Format Strings
修改:如果你的阵列太大而你想避免:
arrStr(1) = String.Format("{0:f2}", NumericUpDown1.Value)
最多arrStr(86) = String.Format("{0:f2}", NumericUpDown86.Value)
您可以使用LINQ创建阵列。假设您的NumericUpDown
控件都位于名为GroupBox
的{{1}}中。您可以“注入”正确的小数位数:
NumericGroupBox
这是一个搜索Dim arrStr() As String =
(From n In NumericGroupBox.Controls.OfType(Of NumericUpDown)()
Select String.Format("{0:f" & n.DecimalPlaces & "}", n.Value)).ToArray()
TabPages
所有TabControl
的版本(如评论所示):
Dim allNumerics = From tp In Me.TabControl1.TabPages.Cast(Of TabPage)()
From n In tp.Controls.OfType(Of NumericUpDown)()
Select String.Format("{0:f" & n.DecimalPlaces & "}", n.Value)
Dim arrStr As String() = allNumerics.ToArray()