0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

BigDecimalを使うときの注意点

Last updated at Posted at 2023-06-16
  • BigDecimalを使うときは、NullPointerExceptionを避けるため、NULLの場合は0を返すようする方が無難である。Stringから変換するときは、以下のようなメソッドを用意しておくと良い!
public static BigDecimal toNumber(String str) {
	if (str == null) {
		return BigDecimal.ZERO;
	} else {
		return new BigDecimal(str.replaceAll(",", ""));
	}
}
  • BigDecimalを直接使う場合も、Optionalを利用してNULLの場合は0を返すようなメソッドを通す方が良い
public static BigDecimal toNumber(BigDecimal num) {
    return Optional.ofNullable(num).orElse(BigDecimal.ZERO)
}
  • ゼロ除算で落ちることを防止するため、以下のようなメソッドを用意しておくと良い
public static BigDecimal divide(BigDecimal num, BigDecimal divisor, int scale, RoundingMode roundingMode) {
	if (divisor.compareTo(BigDecimal.ZERO) == 0) {
		return BigDecimal.ZERO;
	}
	else {
		return num.divide(divisor, scale, roundingMode);
	}
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?