VOOZH about

URL: https://www.geeksforgeeks.org/java/bigdecimal-valueof-method-in-java/

⇱ BigDecimal valueOf() Method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

BigDecimal valueOf() Method in Java

Last Updated : 14 Apr, 2022

java.math.BigDecimal.valueOf(long val) is an inbuilt method in Java that translates a long value into a BigDecimal value with a scale of zero. It allows us, the reuse of frequently used BigDecimal values and hence this "static factory method" is provided in preference to a (long) constructor. Package view is as follows: 

--> java.math Package
 --> BigDecimal Class
 --> valueOf() Method

There are 3 types of variations in valueOf() method of BigDecimal class that are as depicted in syntax below via differing in parameters that are as follows:

  • public static BigDecimal valueOf(long val)
  • public static BigDecimal valueOf(double d)
  • public static BigDecimal value(long l, int x)

Type 1: java.math.BigDecimal.valueOf(long val)

Parameters: The method accepts a single parameter val of Long data type and refers to the value that needs to be translated into a BigDecimal value.

Return value: The method returns a BigDecimal value of Long val.

Example:

Output:

👁 Image

Type 2: java.math.BigDecimal.valueOf(double val)

The java.math.BigDecimal.valueOf(double val) is an inbuilt method in java that translates a double into a BigDecimal, using the double's canonical string representation provided by the Double.toString(double) method.

Syntax: 

public static BigDecimal valueOf(double val)

Parameters: The method accepts a single parameter val of Double data type and refers to the value that needs to be translated into a BigDecimal value.

Return value: The method returns a BigDecimal value which is equal to or approximately equal to Double val

Example:

Output:

👁 Image

Type 3: java.math.BigDecimal.valueOf(long unscaledVal, int scale)

The java.math.BigDecimal.valueOf(long unscaledVal, int scale) is an inbuilt method in Java that is used to translate a long unscaled value and an int scale into a BigDecimal. This "static factory method" is provided in preference to a (long, int) constructor because it allows for reuse of frequently used BigDecimal values.

Syntax: 

public static BigDecimal valueOf(long unscaledVal, int scale)

Parameters: It takes two parameters: 

  • unscaledVal: This is of Long data type and refers to the Unscaled value of the BigDecimal.
  • scale: This is of Integer data type and refers to the Scale of the BigDecimal.

Return Value: A big decimal whose value is unscaled*10-scale.

Example:

Output:

👁 Image

Comment