Java-math-bigdecimal-negate-mc

提供:Dev Guides
移動先:案内検索

Java.math.BigDecimal.negate()メソッド

説明

  • java.math.BigDecimal.negate(MathContext mc)*は、値が(-this)であるBigDecimalを、コンテキスト設定に従った丸めとともに返します。

宣言

以下は* java.math.BigDecimal.negate()*メソッドの宣言です。

public BigDecimal negate(MathContext mc)

パラメーター

*mc* -使用するコンテキスト。

戻り値

このメソッドは、オブジェクトの否定値、つまり、必要に応じて丸められた値を返します。

例外

*ArithmeticException* -結果は正確ではないが、丸めモードがUNNECESSARYの場合。

次の例は、math.BigDecimal.negate()メソッドの使用法を示しています。

package com.finddevguides;

import java.math.*;

public class BigDecimalDemo {

   public static void main(String[] args) {

     //create 2 BigDecimal objects
      BigDecimal bg1, bg2;

      MathContext mc = new MathContext(4);//4 precision

     //assign value to bg1
      bg1 = new BigDecimal("40.1264");

     //assign negate value of bg1 to bg2 using mc
      bg2 = bg1.negate(mc);

      String str = "Negated value, rounded to 2 precision is " +bg2;

     //print bg2 value
      System.out.println( str );
   }
}

上記のプログラムをコンパイルして実行すると、次の結果が生成されます-

Negated value, rounded to 2 precision is -40.13