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

VB.NET如何用Decimal.TryParse同时兼容解析带点号或逗号的十进制字符串

VB.NET 兼容点/逗号小数分隔符的Decimal解析方案

完全不需要修改原始输入字符串,有两种常用实现方式:

方案1:顺序尝试双文化解析(最简实现,推荐)

先尝试解析荷兰比利时地区的逗号分隔格式,解析失败则尝试解析点分隔的通用格式,短路运算不会产生额外性能开销:

Imports System.Globalization

' 变量声明
Dim amountVal As Decimal
' 合并后的解析逻辑
Dim isParseSuccess As Boolean = 
    Decimal.TryParse(amountStr, NumberStyles.AllowDecimalPoint, CultureInfo.CreateSpecificCulture("nl-BE"), amountVal) 
    OrElse 
    Decimal.TryParse(amountStr, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, amountVal)

如果需要支持千位分隔符,将NumberStyles.AllowDecimalPoint替换为NumberStyles.Number即可。

方案2:自定义格式提供器(单次解析实现)

如果希望只执行一次解析逻辑,可以自定义兼容两种分隔符的格式处理类:

Imports System.Globalization
Imports System.Linq

Public Class BeneluxDecimalParser
    Implements IFormatProvider

    Public Function GetFormat(formatType As Type) As Object Implements IFormatProvider.GetFormat
        If formatType Is GetType(NumberFormatInfo) Then
            Dim numInfo As New NumberFormatInfo()
            ' 根据输入字符串动态判断小数分隔符
            If _input.Count(Function(c) c = "."c) = 1 AndAlso _input.Count(Function(c) c = ","c) = 0 Then
                numInfo.NumberDecimalSeparator = "."
            Else
                numInfo.NumberDecimalSeparator = ","
            End If
            Return numInfo
        End If
        Return Nothing
    End Function

    Private _input As String
    Public Sub New(input As String)
        _input = input
    End Sub

    ' 封装TryParse方法
    Public Shared Function TryParse(input As String, ByRef result As Decimal) As Boolean
        Return Decimal.TryParse(input, NumberStyles.AllowDecimalPoint, New BeneluxDecimalParser(input), result)
    End Function
End Class

调用方式非常简洁:

Dim amountVal As Decimal
Dim isParseSuccess As Boolean = BeneluxDecimalParser.TryParse(amountStr, amountVal)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:18:04