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 3 years have passed since last update.

JavaのBigDecimal

Last updated at Posted at 2020-05-20

BigDecimalについて少しまとめた

BigDecimalはJavaのAPIの一つで、
普通の数値型は2進数で処理されるため、意図しない数値が返って来ることがある。
しかし、BigDecimalを使うことで、10進数として扱うことができる。

Number.java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Number {
  public static void main(String[] args) {
    BigDecimal number1 = new BigDecimal("0.2");     //引数は""で囲む
    BigDecimal number2 = new BigDecimal("4");
    System.out.println(number1);
          
    System.out.println(BigDecimal.ZERO);    //0
    System.out.println(BigDecimal.ONE);     //1
    System.out.println(BigDecimal.TEN);     //10

    System.out.println(number1.add(number2));         
    //加算 number1 + number2
    System.out.println(number1.subtract(number2));  
    //減算 number1 - number2
    System.out.println(number1.multiply(number2));  
    //乗算 number1 * number2
    System.out.println(number1.divide(number2, 3, RoundingMode.UP));  
    //除算 number1 / number2, 小数点第3位まで表示, 切り上げ
    //RoundingMode.は切り上げ、切り捨て、四捨五入などがある。

    BigDecimal number3 = new BigDecimal("0.22");
    BigDecimal value1 = number3.scaleByPowerOfTen(2);  //10の2乗
    System.out.println(value1);  //22

    BigDecimal value2 = number3.scaleByPowerOfTen(-2);  //10の-2乗
    System.out.println(value2);  //0.0022

    BigDecimal value3 = number3.negate();  //マイナス化
    System.out.println(value3);   //-0.22
     

  }
}

以上。
まだまだたくさんの機能があるので試してみたいです。

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?