tyoshikawa1106のブログ

- Force.com Developer Blog -

SFDC:ApexでDecimal型数値の整数変換を試してみました

ApexでDecimal型数値の整数変換する方法についてです。
f:id:tyoshikawa1106:20200204080549p:plain

Salesforce Developers


整数変換はround関数で実行できます。
f:id:tyoshikawa1106:20200204080650p:plain

Decimal d = null;
// round
d = 1;
System.debug('d = 1 : ' + d.round());
d = 1.1;
System.debug('d = 1.1 : ' + d.round());
d = 1.4;
System.debug('d = 1.4 : ' + d.round());
d = 1.5;
System.debug('d = 1.5 : ' + d.round());
d = 1.6;
System.debug('d = 1.6 : ' + d.round());
d = 1.9;
System.debug('d = 1.9 : ' + d.round());


上記の場合はこうなります。
f:id:tyoshikawa1106:20200204080732p:plain


round関数にはSystem.RoundingMode.UPやSystem.RoundingMode.DOWNなどのオプションがあります。

System.RoundingMode.UP

f:id:tyoshikawa1106:20200204080843p:plain

Decimal d = null;
// round
d = 1;
System.debug('d = 1 : ' + d.round(System.RoundingMode.UP));
d = 1.1;
System.debug('d = 1.1 : ' + d.round(System.RoundingMode.UP));
d = 1.4;
System.debug('d = 1.4 : ' + d.round(System.RoundingMode.UP));
d = 1.5;
System.debug('d = 1.5 : ' + d.round(System.RoundingMode.UP));
d = 1.6;
System.debug('d = 1.6 : ' + d.round(System.RoundingMode.UP));
d = 1.9;
System.debug('d = 1.9 : ' + d.round(System.RoundingMode.UP));


UPの場合はこうなります。
f:id:tyoshikawa1106:20200204080921p:plain

System.RoundingMode.DOWN

f:id:tyoshikawa1106:20200204081030p:plain

Decimal d = null;
// round
d = 1;
System.debug('d = 1 : ' + d.round(System.RoundingMode.DOWN));
d = 1.1;
System.debug('d = 1.1 : ' + d.round(System.RoundingMode.DOWN));
d = 1.4;
System.debug('d = 1.4 : ' + d.round(System.RoundingMode.DOWN));
d = 1.5;
System.debug('d = 1.5 : ' + d.round(System.RoundingMode.DOWN));
d = 1.6;
System.debug('d = 1.6 : ' + d.round(System.RoundingMode.DOWN));
d = 1.9;
System.debug('d = 1.9 : ' + d.round(System.RoundingMode.DOWN));

DOWNの場合はこうなります。
f:id:tyoshikawa1106:20200204081146p:plain


他にもいくつかオプションが用意されているので開発者ガイドで確認するのがいいと思います。