BigDecimal creation

In this chapter you will learn:

  1. How to create Java BigDecimal
  2. How to create BigDecimal from MathContext

Create BigDecimals

BigDecimal(double val) converts a double into a BigDecimal.

import java.math.BigDecimal;
 /* j a v a2s.co  m*/

public class Main {
 
    public static void main(String[] args) {
        System.out.println(new BigDecimal(1f));
        System.out.println(new BigDecimal(2f));
        
    }
}

The output:

Create BigDecimal from MathContext

BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) converts a BigInteger and an int scale into a BigDecimal, with rounding according to the context settings.

import java.math.BigDecimal;
import java.math.MathContext;
 //  ja v  a 2  s.  co  m

public class Main {
 
    public static void main(String[] args) {
        BigDecimal first = new BigDecimal(1f);
        BigDecimal second = new BigDecimal(1000f);
 
 
        BigDecimal result1 = new BigDecimal(first.doubleValue() / second.doubleValue());
        BigDecimal result2 = first.divide(second, MathContext.DECIMAL128);
 
        System.out.println(result1);
        System.out.println(result2);
        System.out.println((first.doubleValue() / second.doubleValue()));
 
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What methods to use to do calculation on BigDecimal
  2. How to get absolute value from BigDecimal
  3. How to add two BigDecimal value together
  4. Calculating Euler's number e with BigDecimal
  5. Multiply one BigDecimal to another BigDecimal
Home » Java Tutorial » BigDecimal BigInteger

BigDecimal

    BigDecimal
    BigDecimal constants
    BigDecimal Rounding mode
    BigDecimal creation
    BigDecimal calculation
    BigDecimal convert
    BigDecimal Comparison
    BigDecimal to String
    BigDecimal decimal point
    BigDecimal precision
    BigDecimal format

BigInteger

    BigInteger class
    BigInteger creation
    BigInteger add, subtract, multiply and divide
    BigInteger power and modPow
    BigInteger conversion
    BigInteger to String
    BigInteger bit and,or,xor,test,flip,negate
    BigInteger bit shift left and right
    BigInteger prime value
    BigDecimal
    BigDecimal constants
    BigDecimal Rounding mode
    BigDecimal creation
    BigDecimal calculation
    BigDecimal convert
    BigDecimal Comparison
    BigDecimal to String
    BigDecimal decimal point
    BigDecimal precision
    BigDecimal format