自動データ型変換

LotusScript® では、あるデータ型から別のデータ型に値を自動的に変換できます。自動的または暗黙的なデータ型変換は、次のような場合に行われます。

注: 常に値の変換が可能というわけではありません。変換できない場合には、型の不一致エラーが発生します。
注: 予期しない結果を避けるため、できる限り明示的な変換を使用することをお勧めします。

例 1

' This example illustrates the automatic conversion
' of decimal numbers to integers that happens when you perform
' integer division and when you assign a decimal number value
' to an integer variable.
Dim anInt As Integer
Dim aDouble As Double
' Do floating-point division.
anInt% = 12/7
Print anInt%
' Output: 2
aDouble# = 12/7
Print aDouble#
' Output: 1.71428571428571
' Do integer division.
anInt% = 12¥7
Print anInt%
' Output: 1
aDouble# = 12¥7
Print aDouble#
' Output: 1

' Do floating-point division.
anInt% = 12.5/2
Print anInt%
' Output: 6
aDouble# = 12.5/2
Print aDouble#
' Output: 6.25

' Do integer division.
anInt% = 12.5¥2
Print anInt%
' Output: 6
aDouble# = 12.5¥2
Print aDouble#
' Output: 6

例 2

次の例では、値 1.6 が X に代入されます。X は Integer 型の変数なので、1.6 は代入が行われる前に整数に変換されます。浮動小数点数値 (単精度と倍精度の値) から整数値 (Integer と Long 値) への変換では、値は最も近い整数に丸められます。この場合は 2 になります。

1.5 が Y に代入される場合、LotusScript によって最も近い偶数の整数 2 に丸められます。浮動小数点数値が 2 つの整数値のちょうど半分である場合、常に最も近い偶数の整数値に丸められます。したがって、値 2.5 は Z に代入されるときに 2 に丸められます。値 3.5 は 4 に、値 -3.5 は -4 に丸められます。値 0.5 と -0.5 はゼロに丸められます。

Dim X As Integer
Dim Y As Integer
Dim Z As Integer
X% = 1.6
Print X%
' Output: 2
Y% = 1.5
Print Y%
' Output: 2
Z% = 2.5
Print Z%
' Output: 2

例 3

次の例では、Variant 型の変数でのデータ型変換が、数値に対応してどのように処理されるかを示しています。

Dim sumV As Variant
Dim sInt As Integer
sInt% = 42
sumV = sInt% 
Print TypeName(sumV)
' Output: INTEGER
 
' Assign the largest integer value to sInt%.
sInt% = 32767
sumV = sInt% + 1
' LotusScript converts sumV to a Long to prevent 
' an overflow.
Print TypeName(SumV)
' Output: LONG

例 4

次の例では、Variant 型の変数が + 演算子を伴う演算のオペランドである場合に、LotusScript が「数値から文字列」と「文字列から数値」の変換を行う様子を示しています。+ 演算子は、加算にも文字連結にも使用できます。

Dim aVariantV As Variant
aVariantV = 1040
Print TypeName(aVariantV)
' Output: INTEGER
Print aVariantV + "A"
' Output: 1040A
' because "A" is a string and 1040 can be interpreted as a string.
aVariantV = "43"
Print TypeName(aVariantV)
' Output: STRING
Print aVariantV + 5
' Output: 48
' because 48 is a number and 5 can be interpreted as a number.