You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VB.NET中将多个Double类型变量的值以竖线分隔写入.txt文件的同一行?

Solution to Write Double Variables to Text File with Pipe Separator

Got it, the issue here is that you're writing literal strings instead of referencing your actual V1, V2, V3 variables. Let's fix this with a few clean, reliable approaches—plus I'll throw in a best practice for file handling to avoid headaches later.

First, the Core Fix: Reference Your Variables

Instead of hardcoding "The Value of V1", you need to use the variables themselves. VB.NET will automatically convert Double values to strings when concatenating, but you can also explicitly format them if you need control over decimal places, etc.

Option 1: String Concatenation (Straightforward)

' First, make sure your variables are initialized with values!
Dim V1 As Double = 15.67
Dim V2 As Double = 89.01
Dim V3 As Double = 42.34

' Use Using statement to auto-close the file (safer than manual Close())
Using file As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("test.txt", True)
    file.WriteLine(V1 & "|" & V2 & "|" & V3)
End Using

Option 2: String.Format (Cleaner for Multiple Values)

This makes the structure easier to read, especially if you add formatting later:

Dim V1 As Double = 15.67
Dim V2 As Double = 89.01
Dim V3 As Double = 42.34

Using file As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("test.txt", True)
    file.WriteLine(String.Format("{0}|{1}|{2}", V1, V2, V3))
End Using

Option 3: String Interpolation (Modern VB.NET)

If you're using Visual Studio 2015 or later, interpolation is the most intuitive way:

Dim V1 As Double = 15.67
Dim V2 As Double = 89.01
Dim V3 As Double = 42.34

Using file As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("test.txt", True)
    file.WriteLine($"{V1}|{V2}|{V3}")
End Using

Bonus: Control Number Formatting

If you need to specify decimal places (e.g., 2 decimal places), modify the variable references like this:

  • Concatenation: V1.ToString("F2")
  • String.Format: "{0:F2}|{1:F2}|{2:F2}"
  • Interpolation: $"{V1:F2}|{V2:F2}|{V3:F2}"

Why Use Using?

The Using statement automatically disposes of the StreamWriter when it's done, even if an error occurs. This avoids leaving the file locked or unclosed, which is a common pitfall with manual Close() calls.

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:02:28