You can use Math.pow()
to compute powers. pow means power, and power means power.
Pass a and b as arguments to pow()
and return a to the power of b. That is, a multiplied by b times is returned.
// Math.java
public static double pow(double a, double b)
We can calculate 3.2 to the third power as follows:
double result = Math.pow(3.2, 3);
System.out.println(result);
Running it returns about 32.76. This value is equivalent to 3.2 * 3.2 * 3.2
.
32.76800000000001
If you want to convert to int, you have to cast it directly like this:
int result = (int) Math.pow(3.2, 3);
output format
If you use DecimalFormat
, you can make it output only to a few decimal places.
DecimalFormat df = new DecimalFormat(".00");
double result = Math.pow(3.2, 3);
System.out.println(df.format(result));
Output:
32.77
Example
If the second argument is 0, 1 is returned.
double result = Math.pow(3.2, 0);
System.out.println(result);
Output:
1.0
If the second argument is 1, 3.2 is returned.
double result = Math.pow(3.2, 1);
System.out.println(result);
Output:
3.2
If the second argument is NaN(Not a Number), NaN is returned.
double result = Math.pow(3.2, Double.NaN);
System.out.println(result);
Output:
NaN
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)