切捨ての解釈

友人から質問受けて調べたのですが、


質問:「NumberFormatterの切捨てってバグじゃない?」


答え:バグではありませんでした。


なんのことかって、マイナス値の小数点を切り捨てたときに、


 -1.5の小数点を切り捨てて -2 になります。


僕もアレ?って思ったのですが、調べてみたら面白かったです。

Flex 1.5の場合

・ソース

var numFormat:NumberFormatter = new NumberFormatter();
numFormat.precision = 0;
numFormat.rounding = "down";

・結果

1.5 -> 1
-1.5 -> -2

ActionScript2.0の場合

・ソース

Math.floor()

・結果

1.5 -> 1
-1.5 -> -2

Excel VBAの場合

・ソース

Private Sub CommandButton1_Click()
    Dim s As Single

    For s = -2 To 2 Step 0.5
       MsgBox ("s=" & s & " Int(s)=" & Int(s) & " Int(-s)=" & Int(-s) &
"   s=" & s & " Fix(s)=" & Fix(s) & " Fix(-s)=" & Fix(-s))
    Next
End Sub

・実行結果

s=-1.5 Int(s)=-2 Int(-s)=1
s=-1.5 Fix(s)=-1 Fix(-s)=1

Oracle SQLの場合

・ソース

SELECT TRUNC(1.5, 0) DP1 ,TRUNC(-1.5, 0) DP2 FROM DUAL;

・実行結果

1 
-1

Javaの場合

・ソース

double a = 1.5;
double b = -1.5;
System.out.println(Math.floor(a));
System.out.println(Math.floor(b));

・実行結果

1.0
-2.0

まとめます

Flex:numFormat.rounding = "down"は、小さい値の方向で切捨て
Flash:Math.floor()は、小さい値の方向で切捨て
Excel:Int()は、小さい値の方向で切捨て
  :Fix()は、絶対値に切捨て
Java:Math.floor()は、小さい値の方向で切捨て
Oracle:Trunc()は、絶対値に切捨て