- Java.math package classes
- Java.math - Home
- Java.math - BigDecimal
- Java.math - BigInteger
- Java.math - MathContext
- Java.math package extras
- Java.math - Enumerations
- Java.math - Discussion
Java.math.BigDecimal.abs() Method
Description
The java.math.BigDecimal.abs(MathContext mc) returns a BigDecimal whose value is the absolute value of this BigDecimal, with rounding according to the context settings.
Declaration
Following is the declaration for java.math.BigDecimal.abs() method.
public BigDecimal abs(MathContext mc)
Parameters
mc − The context to use.
Return Value
This method returns the absolute value of the called value i.e abs(this), rounded as necessary.
Exception
ArithmeticException − If the result is inexact but the rounding mode is UNNECESSARY.
Example
The following example shows the usage of math.BigDecimal.abs() method.
package com.tutorialspoint; import java.math.*; public class BigDecimalDemo { public static void main(String[] args) { // create 3 BigDecimal objects BigDecimal bg1, bg2, bg3; MathContext mc = new MathContext(2); MathContext mc1 = new MathContext(4); // assign value to bg1 bg1 = new BigDecimal("40.1234"); // assign absolute value of bg1 to bg2 rounded to 2 precision using mc bg2 = bg1.abs(mc); // assign absolute value of bg1 to bg3 rounded to 4 precision using mc1 bg3 = bg1.abs(mc1); String str1,str2; str1 = "Absolute value, rounded to 2 precision is " + bg2; str2 = "Absolute value, rounded to 4 precision is " + bg3; // print bg2 and bg3 value System.out.println( str1 ); System.out.println( str2 ); } }
Let us compile and run the above program, this will produce the following result −
Absolute value, rounded to 2 precision is 40 Absolute value, rounded to 4 precision is 40.12
java_math_bigdecimal.htm
Advertisements