汎用関数は次のように記述できます。
public static double round(double inputNumber, int fractionDigits, int roundingMode) {
BigDecimal bigDecimal = new BigDecimal(inputNumber);
BigDecimal rounded = bigDecimal.setScale(fractionDigits, roundingMode);
return rounded.doubleValue();
}
以下のサンプルテスト結果をご覧ください。
import java.math.BigDecimal;
public class RoundHelper {
public static void main(String[] args) {
System.out.println(RoundHelper.round(123.98980, 2, BigDecimal.ROUND_HALF_UP));
System.out.println(RoundHelper.round(123.98000, 2, BigDecimal.ROUND_HALF_UP));
System.out.println(RoundHelper.round(123.98000, 2, BigDecimal.ROUND_HALF_UP));
System.out.println(RoundHelper.round(123.55087, 2, BigDecimal.ROUND_HALF_UP));
System.out.println(RoundHelper.round(123.14000, 2, BigDecimal.ROUND_HALF_UP));
}
public static double round(double inputNumber, int fractionDigits, int roundingMode) {
BigDecimal bigDecimal = new BigDecimal(inputNumber);
BigDecimal rounded = bigDecimal.setScale(fractionDigits, roundingMode);
return rounded.doubleValue();
}
}
出力:
123.99
123.98
123.98
123.55
123.14