Previous | Home | Next |
While programming if the precision of the integers and floating point number is not according to the requirements, then we can use the big numbers defined in java.
the big numbers are contained in java.math package, BigInteger is used for manipulating the precision of the integral values while BigDecimal is used for the floating point numbers. The method valueOf(), defined in the package can turn any ordinary number to a big number.
BigInteger num = BigInteger.valueOf(300);
In this example we have converted a simple integer 300 to a BigInteger type value and assigned it to the num. Also note that we cannot use basic operators like +, -, /, * directly on the big numbers, infact we have to use predefined methods like add(), multiply() in order to combine the big numbers. For e.g.
BigInteger num = BigInteger.valueOf(300); BigInteger p = num.add(BigInteger.valueOf(200)); // it goes as p=num+200= 300+200=500
Some of the methods which are defined in java.math.BigInteger class and used more commonly are :
BigInteger add(BigInteger second) // returns the sum of current BigInteger with the second BigInteger multiply(BigInteger second) // returns the multiplication of current BigInteger with the second BigInteger divide(BigInteger second) // returns the division of current BigInteger with the second BigInteger subrtact(BigInteger second) // returns the subtraction of current BigInteger with the second BigInteger mod(BigInteger second) // return the mod value of current BigInteger with the second
int Java TutorialsompareTo(BigInteger second)
It compares the value of the current BigInteger with the second and then returns an integral value. If current number is greater than second than it will give a positive integer, if equal it will return 0, else it will return a negative value.
static BigInteger valueOf(Long p)
It converts an integer number to the Big Integer type number.
Similarly we can use BigDecimal class to manipulating the precision of the floating point numbers. The frequent methods which are defined in the java.math.BigDecimal class are :
BigDecimal add(BigDecimal second) // returns the sum of current BigDecimal with the second BigDecimal multiply(BigDecimal second) // returns the multiplication of current BigDecimal with the second BigDecimal divide(BigDecimal second, int roundoff mode) //returns the divison of current BigDecimal with second one with roundoff digits BigDecimal subrtact(BigDecimal second) // returns the subtraction of current BigDecimal with the second int Java TutorialsompareTo(BigDecimal second) // return an integer after comparing the two BigDecimal type numbers static BigDecimal valueOf(Long p) // convert an simple number to the BigDecimal type number static BigDecimal valueOf(Long p, int scale) // converts an simple to the BigDecimal number x /10^scale
Previous | Home | Next |