文字列から数値型への変換は以下のページにありますが、今回はオブジェクト型から数値への変換を記します。
⇒文字列から数値型への変換(parse - tryparse)
Integer型に変換するために Integer.TryParse メソッドを使いますが、引数としては文字列なので 先ずはオブジェクト型から文字列型への変換関数を宣言します。 ソースは以下の様になります。(Objectデータが「Nothing」「DBNULL」の場合には空文字列を返します。)
オブジェクト型からString型への変換
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | ''' <summary> ''' Object型からString型にデータ変換 ''' </summary> ''' <param>元のObject</param> ''' <returns>String型に変換後の値</returns> ''' <remarks>String型に変換できない場合は「""」を返す</remarks> Function ObjToStr( ByVal objSrc As Object ) As String Dim strRet As String Try If objSrc Is Nothing Then 'Objectデータが「Nothing」の場合 strRet = "" ElseIf IsDBNull(objSrc) Then 'Objectデータが「DBNULL」の場合 strRet = "" Else '文字列に変換 strRet = CStr (objSrc) End If Catch ex As Exception 'エラーの場合 strRet = "" End Try '変換値を返す Return strRet End Function |
このオブジェクト型から文字列型への変換関数を利用して、 オブジェクト型からInteger型への変換関数を宣言します。
オブジェクト型からInteger型への変換
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | ''' <summary> ''' Object型からInteger型にデータ変換 ''' </summary> ''' <param>元のObject</param> ''' <returns>Integer型に変換後の値</returns> ''' <remarks>Integer型に変換できない場合は「0」を返す</remarks> Function ObjToInt( ByVal objSrc As Object ) As Integer Dim intRet As Integer Try 'String型に変換 Dim strSrc As String = ObjToStr(objSrc) 'Integer型に変換 If Integer .TryParse(strSrc, intRet) = False Then '変換が不可の場合 intRet = 0 End If Catch ex As Exception 'エラーの場合 intRet = 0 End Try '変換値を返す Return intRet End Function |
更にオブジェクト型からDecimal型への変換は以下の様になります。 (その他のDouble型とかも同様に宣言できます)
オブジェクト型からDecimal型への変換
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | ''' <summary> ''' Object型からDecimal型にデータ変換 ''' </summary> ''' <param>元のObject</param> ''' <returns>Decimal型に変換後の値</returns> ''' <remarks>Decimal型に変換できない場合は「0」を返す</remarks> Function ObjToDec( ByVal objSrc As Object ) As Decimal Dim decRet As Decimal Try 'String型に変換 Dim strSrc As String = ObjToStr(objSrc) 'Decimal型に変換 If Decimal .TryParse(strSrc, decRet) = False Then '変換が不可の場合 decRet = 0 End If Catch ex As Exception 'エラーの場合 decRet = 0 End Try '変換値を返す Return decRet End Function |
コメント