Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is NumberUtils.createDouble in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

createDouble() is a staticthe methods in Java that can be called without creating an object of the class. method of the NumberUtils class that is used to convert a string to a Double datatype. If the string cannot be converted to a double value, then createDouble() will throw NumberFormatException.

How to import NumberUtils

The definition of NumberUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

You can import the NumberUtils class as follows:


import org.apache.commons.lang3.math.NumberUtils;

Syntax


public static Double createDouble(final String str)

Parameters

  • final String str: The string to convert.

Return value

This method returns the converted double value.

Code

import org.apache.commons.lang3.math.NumberUtils;
public class Main{
public static void main(String[] args){
// Example 1
String valueToConvert = "234323232.232123";
System.out.printf("NumberUtils.createDouble(%s) = %s", valueToConvert, NumberUtils.createDouble(valueToConvert));
System.out.println();
// Example 2
valueToConvert = "234323wrf";
System.out.printf("NumberUtils.createDouble(%s) = %s", valueToConvert, NumberUtils.createDouble(valueToConvert));
System.out.println();
}
}

Example 1

  • string value = 234323232.232123

The method returns 234323232.232123, as the conversion is successful.

Example 2

  • string value = 234323wrf

The method throws NumberFormatException, as the conversion is unsuccessful.

Output

The output of the code will be as follows:


NumberUtils.createDouble(234323232.232123) = 2.34323232232123E8

Exception in thread "main" java.lang.NumberFormatException: For input string: "234323wrf"

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring