最も近い百に切り上げる

最も近い百に切り上げる

1. 概要

このクイックチュートリアルでは、round up a given number to the nearest hundredを実行する方法を説明します。

例:99100になります200.2300になります400400になります

2. 実装

まず、入力パラメータでMath.ceil()を呼び出します。 Math.ceil() returns the smallest integer that is greater than or equal to the argument.たとえば、入力が200.2の場合、Math.ceil()は201を返します。

次に、結果に99を追加し、100で除算します。 整数divisionto truncate the decimal portion of the quotient.を利用しています。最後に、商に100を掛けて、目的の出力を取得します。

実装は次のとおりです。

static long round(double input) {
    long i = (long) Math.ceil(input);
    return ((i + 99) / 100) * 100;
};

3. テスト

実装をテストしてみましょう。

@Test
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
    assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
    assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
    assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
}

4. 結論

この簡単な記事では、数値を百の位まで切り上げる方法を示しました。

いつものように、完全なコードはon the GitHubで利用できます。