+ 2

In java, is there any data type having range more than the range of the primitive data type "double" to store no.?

i.e. if I want to store a too large no. is out of the range of double data type... then how can i store that no.

26th Feb 2017, 5:34 AM
NEERAJ CHOUHAN
NEERAJ CHOUHAN - avatar
3 Réponses
+ 3
double is the "biggest" primitive type, you'd have to use the BigDecimal class for larger numbers and more precision. Working with BigDecimal is a bit more complicated, since you cannot use +, -,..  operators directly. Example: import java.math.BigDecimal; public class Program { public static void main(String[] args) { BigDecimal num = new BigDecimal("1234567890.987654321"); System.out.println("Value is " + num); num = num.multiply(new BigDecimal(100000000L)); System.out.println("Value is " + num); } }
26th Feb 2017, 6:27 AM
Tero Särkkä
Tero Särkkä - avatar
+ 3
ok... thanks Tero Särkkä...But if I am comparing two BigDecimal numbers then it is an error... import java.math.BigDecimal; public class Program { public static void main(String[] args) { BigDecimal num1 = new BigDecimal("1234567890.987654321"); System.out.println("Value is " + num1); num2 = num1.multiply(new BigDecimal(100000000L)); System.out.println("Value is " + num2); if(num1<num2) //comparing two BigDecimal numbers but it is an error System.out.println("yes"); } } In this code I want to print "yes" because num1 is less than num2 ... so how can i compare their values and print "yes".
26th Feb 2017, 10:59 AM
NEERAJ CHOUHAN
NEERAJ CHOUHAN - avatar
+ 2
You can use compareTo method for comparisons. It returns -1, 0 or 1, depending on whether the number is smaller, equal or greater than the given parameter. So in your case: if (num1.compareTo(num2) == -1) {.... }
26th Feb 2017, 11:05 AM
Tero Särkkä
Tero Särkkä - avatar