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.
Este exercício faz parte do curso
Data Types and Exceptions in Java
Instruções do exercício
- Import the
BigDecimalclass fromjava.math. - Create an instance of
BigDecimalto hold the number9.123456789. - Multiply the
BigDecimalin variablebigDecbyten. - Divide the
BigDecimalin variablebigDecbyhundred.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
// 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);
}
}