0
0

More than 1 year has passed since last update.

【Java】BigDecimal

Posted at

BigDecimalとは

  • 誤差が出ないように正確に計算するためのクラス
  • 四捨五入などの丸め処理ができる
  • 桁数の指定ができる

BigDecimalを使わない場合にどのような誤差が出るのか

import java.math.BigDecimal;

public class Main {
  public static void main(String[] args) {
    // BigDecimalを使わない場合
    System.out.println(1 - 0.9); // 0.09999999999999998

    // BigDecimalを使う場合
    BigDecimal number1 = BigDecimal.valueOf(1);
    BigDecimal number2 = BigDecimal.valueOf(0.9);
    System.out.println(number1.subtract(number2)); // 0.1
  }
}
0
0
4

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