Curl Global Community
BigDecimal の丸め - Printable Version

+- Curl Global Community (https://communities.curl.com)
+-- Forum: Discussions (https://communities.curl.com/forumdisplay.php?fid=1)
+--- Forum: General Curl questions (https://communities.curl.com/forumdisplay.php?fid=2)
+--- Thread: BigDecimal の丸め (/showthread.php?tid=1188)



BigDecimal の丸め - umemura - 11-20-2014

BigDecimal の RoundingMode で毎回悩むので、メモ。

Code:
{def fr = {Frame}}
{def ary-rounding-mode =
    {{Array-of RoundingMode}
        RoundingMode.away-from-zero         || ゼロから遠いほうへ近づける
        , RoundingMode.ceiling              || 切り上げ(天井)
        , RoundingMode.floor                || 切り下げ(床)
        , RoundingMode.round-away-from-zero || 四捨五入
        , RoundingMode.round-toward-even    || 絶対値1以下五捨六入、絶対値1以上四捨五入?
        , RoundingMode.round-toward-zero    || 五捨六入
        , RoundingMode.truncate             || 小数点以下切り捨て
    }
}
{def test-data =
    {StringArray
        "-1.9", "-1.6", "-1.5", "-1.4", "-1.1",
        "-0.9", "-0.6",  "-0.5",  "-0.4", "-0.1" ,
        ||"0",
        "0.1","0.4", "0.5", "0.6", "0.9",
        "1.1", "1.4", "1.5", "1.6", "1.9"
    }
}
{def scale-tf = {TextField value = "0"}}
{def val-tf = {TextField value = "0.1"}}
{VBox
    {Table columns = 2, "スケール位置", scale-tf, "値", val-tf},
    {CommandButton
        label = "丸め結果一覧",
        {on Action do

            def scale = {scale-tf.value.to-int}
            def s = val-tf.value
            def tbl = {Table halign = "right", columns = 2 , "モード/元値", s}
            {for mode in ary-rounding-mode do
                {tbl.add mode}
                def bd = {BigDecimal.from-String s}
                def trun-bd = {bd.set-scale scale, rounding-mode = mode}
                {tbl.add {trun-bd.to-String}}
            }
            {popup-message tbl}
        }
    }
    ,{CommandButton
         label = "テストデータ:丸め結果一覧",
         {on Action do
             def scale = {scale-tf.value.to-int}
             def tbl = {Table halign = "right", columns =test-data.size + 1 , "モード/元値"}

             {for s in test-data do
                 {tbl.add s}
             }
             {for mode in ary-rounding-mode do
                 {tbl.add mode}
                 {for s in test-data do
                     def bd = {BigDecimal.from-String s}
                     def trun-bd = {bd.set-scale scale, rounding-mode = mode}
                     {tbl.add {trun-bd.to-String}}
                 }
             }
             {fr.add replace? = true, tbl}
         }
    }
}

{value fr}