CKTIS / Java
BigDecimal.valueOf — creating decimal values
Learn the three `BigDecimal.valueOf` overloads in Java 21 and why converting a `double` with the factory can differ from passing it to the constructor.
Version: Java SE 21
Syntax
import java.math.BigDecimal;
// Static overloads declared by java.math.BigDecimal:
public static BigDecimal valueOf(long val)
public static BigDecimal valueOf(long unscaledVal, int scale)
public static BigDecimal valueOf(double val)BigDecimal.valueOf is a static factory method on java.math.BigDecimal. After adding import java.math.BigDecimal;, call it on the class name without new. Java SE 21 provides three overloads.
valueOf(long) preserves the integer value and sets the scale to 0. valueOf(long unscaledVal, int scale) returns the exact value unscaledVal × 10^(−scale) with the specified scale. For example, BigDecimal.valueOf(1250L, 2) gives 12.50 with scale 2. Scale can be negative: BigDecimal.valueOf(125L, -2) has numeric value 12500 and scale -2.
For a finite double d, valueOf(double) gives the same result as new BigDecimal(Double.toString(d)): it uses the canonical decimal text for d. By contrast, new BigDecimal(d) represents the exact binary value stored in d as a decimal. So BigDecimal.valueOf(0.1) gives exactly 0.1, while new BigDecimal(0.1) gives a slightly larger value. Both forms throw NumberFormatException for NaN and either infinity.
Conversion cannot recover precision that was already lost. In BigDecimal.valueOf(0.1 + 0.2), the addition happens in double first, so the result is 0.30000000000000004. If you start with exact decimal text, use new BigDecimal("0.1") rather than going through double. There is no BigDecimal.valueOf(String) overload.
Examples
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
double input = 0.1;
System.out.println(BigDecimal.valueOf(input).toPlainString());
System.out.println(new BigDecimal(input).toPlainString());
System.out.println(BigDecimal.valueOf(125L).toPlainString());
System.out.println(BigDecimal.valueOf(1250L, 2).toPlainString());
System.out.println(BigDecimal.valueOf(0.1 + 0.2).toPlainString());
}
}Result
0.1 0.1000000000000000055511151231257827021181583404541015625 125 12.50 0.30000000000000004
The first two lines compare the factory and constructor for the same `double`. The third and fourth show the integer overloads, and the last shows the effect of earlier `double` addition. `toPlainString()` returns the value as text without exponent notation, and `println` prints that text.
Related lessons
- Java · Lesson 4 · Basic · Version: 2
- Java · Lesson 6 · Basic · Version: 2