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?

API(BigDecimalクラス)の活用

Posted at
Ex1_15_1
import java.math.BigDecimal;
import java.math.RoundingMode;

class Ex1_15_1{
	public static void main (String[] args) {
		
		//(1) 0.2 * 83 - 10.6
		BigDecimal b1 = new BigDecimal( "0.2" );
		BigDecimal b2 = new BigDecimal( "83" );
		BigDecimal b3 = new BigDecimal( "10.6" );
		
		BigDecimal result1 = ( b1.multiply( b2 ) ).subtract(b3);
		System.out.println(result1);
		
		//(2) 0.2 * 83 - 10.6 / 3 ※小数第4位までで表示(小数第5位以下は四捨五入)
		
		BigDecimal b4 = new BigDecimal( "3" );
		BigDecimal result2 = ( b1.multiply( b2 ) ).subtract( b3.divide( b4, 4, RoundingMode.HALF_UP));
		System.out.println(result2);
		
	}
}

今回は、API(BigDecimalクラス)を使用した計算を行った。厳密な小数の計算をする際に特殊な処理が必要になるためBigDecimalを使用する。

~~~BigDecimalを使うにあたって~~~
・classの前にimport文でBigDecimalを使えるようにする。
・BigDecimalで数字を定義するときに””を付ける。
└10進数の数字は2進数に変換するときに表現できない数字があるため。文字列として扱うことで、10進数の世界で数値化する機能がBigDecimalに備わっている。
・四則演算用のメソッドは以下を使う

四則演算
足し算add()
引き算subtract()
掛け算multiply()
割り算divide()

・丸め処理の方法(import文にRoundingModeを記載)

丸め処理
四捨五入RoundingMode.HALF_UP
切り上げRoundingMode.UP
切り捨てRoundingMode.DOWN
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?