Using math classes
Classes from java.math
can be a bit more difficult to work with, but offer the ability to work with larger numbers and are more precise. In this exercise, you'll see the precision difference between a double
and a BigDecimal
from java.math
.
This exercise is part of the course
Data Types and Exceptions in Java
Exercise instructions
- Import the
BigDecimal
class fromjava.math
. - Create an instance of
BigDecimal
to hold the number9.123456789
. - Multiply the
BigDecimal
in variablebigDec
byten
. - Divide the
BigDecimal
in variablebigDec
byhundred
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
// Import BigDecimal
import ___.___.___;
public class HelloWorld {
public static void main(String[] args) {
double d = 9.123456789;
// Create a BigDecimal with the value of 9.123456789
BigDecimal bigDec = ____ ____(____);
BigDecimal ten = new BigDecimal(10);
BigDecimal hundred = new BigDecimal(100);
d = d*10;
d = d/100;
// Multiply bigDec by ten
bigDec = ____.____(____);
// Divide bigDec by hundred
bigDec = ____.____(____);
System.out.println(d);
System.out.println(bigDec);
}
}