BigDecimal data type Vs Double

618 views Asked by At

There is a class written by Jama Matrix in Java. The class is like that

public Matrix (int m, int n, double s) {
  this.m = m;
  this.n = n;
  A = new double[m][n];
  for (int i = 0; i < m; i++) {
     for (int j = 0; j < n; j++) {
        A[i][j] = s;
     }
  }
}

It can create a matrix with m*n dimension whose datatype is double that means it take 6 digit after point(.). But I need a matrix which can take minimum 10 digit after point(like 12.1234567890). So after searching I find BigDecimal data type which can take this type of value. So I slightly modify the previous code.

 public Matrix(int m,int n,BigDecimal s){
   this.m=m;
   this.n=n;
   A= new BigDecimal[m][n];
   for(int i=0;i<m;i++){
       for(int j=0;j<n;j++){
           A[i][j]=s;
       }
   }
}

But it throws error. Is there any other datatype which is used in java for floating point number.

I am little bit confused when run this code

 public class T {
public static void main(String args[]){
    double a= 3.256147001235;
    double b=4.200001258920;
    double c=a+b;
    System.out.println(c);
}
 }

Here datatype is also double but the output is 7.456148260155. So here it take this big number but in matrix class it cannot take this big number.

1

There are 1 answers

4
Sergey Kalinichenko On

Unlike double or String, BigDecimal does not have built-in support from Java compiler for constructing objects with literals. You need to construct it either with a constructor or by calling valueOf, depending on the source of data:

Matrix bigDecimalMatrix = new Matrix(100, 80, BigDecimal.valueOf(4.200001258920));

or

Matrix bigDecimalMatrix = new Matrix(100, 80, new BigDecimal("4.200001258920"));

Similarly, BigDecimal does not have compiler support for running arithmetic operations. Hence, instead of

double c = a + b;

you would need to write

BigDecimal c = a.add(b);