BigDecimal convert
In this chapter you will learn:
- How to convert BigDecimal to primitive data types
- How to convert to float type value
- Convert double and long to BigDecimal
Convert BigDecimal to primitive data types
We can use the following methods to convert BigDecimal values to primitive data types.
byte byteValueExact()
Converts this BigDecimal to a byte, checking for lost information.double doubleValue()
Converts this BigDecimal to a double.float floatValue()
Converts this BigDecimal to a float.int intValue()
Converts this BigDecimal to an int.int intValueExact()
Converts this BigDecimal to an int, checking for lost information.long longValue()
Converts this BigDecimal to a long.long longValueExact()
Converts this BigDecimal to a long, checking for lost information.short shortValueExact()
Converts this BigDecimal to a short, checking for lost information.BigInteger toBigInteger()
Converts this BigDecimal to a BigInteger.BigInteger toBigIntegerExact()
Converts this BigDecimal to a BigInteger, checking for lost information.
Convert to float type value
floatValue()
method is used in the following code to convert
BigDecimal value to float type value.
import java.math.BigDecimal;
// j a v a2 s. c o m
public class Main {
public static void main(String[] args) {
BigDecimal first = new BigDecimal(-1f);
System.out.println(first.floatValue());
}
}
The output:
Convert double and long to BigDecimal
static BigDecimal valueOf(double val)
Translates a double into a BigDecimal.static BigDecimal valueOf(long val)
Translates a long value into a BigDecimal with a scale of zero.static BigDecimal valueOf(long unscaledVal, int scale)
Translates a long unscaled value and an int scale into a BigDecimal.
import java.math.BigDecimal;
//j a v a 2 s .c o m
public class Main {
public static void main(String[] args) {
System.out.println(BigDecimal.valueOf(1.00001));
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » BigDecimal BigInteger