1. Overview
The power of a number means how many times to use the number in multiplication. This can be easily calculated in Java.
2. Math.pow Example
Before looking at the example, let’s look at the method’s signature:
public double pow(double a, double b)
The method raises a to the power of b and returns the result as double. In other words, a is multiplied by itself b times.
Let’s look at a simple example now:
int intResult = (int) Math.pow(2, 3);
The output will be 8. Please note that the int casting in the above example is required if we want to have an Integer result.
Let’s now pass a double as an argument and see the results:
double dblResult = Math.pow(4.2, 3);
The output will be 74.08800000000001.
Here we’re not casting the result to an int as we are interested in a double value. Since we have a double value, we can easily configure and use a DecimalFormat to round the value to two decimal places, resulting in 74.09:
DecimalFormat df = new DecimalFormat(".00");
double dblResult = Math.pow(4.2, 3);
3. Conclusion
In this quick article, we have seen how to use the Java’s Math.pow() method to calculate the power of any given base.
Like always, the full source code is available over on GitHub.