Java Read Property Value as Double

Tags: Properties PropertiesUtils

In this Java tutorial, we learn how to write a Java utility class to load the properties file and read a property value as a Double value in Java programming language.

How to get property value as a Double value in Java

For example, we have a properties file named application.properties located under resources directory in your Java project with the file content as below.

src/main/resources/application.properties

taxPercentage=0.1

At this first step, create a new Java class named PropertiesUtils.

In this new class, implement a static Java code block to load the application.properties file into the Properties object.

And then implement a new static method named getDouble(String key) to get the property value as a Double value as Java code below.

PropertiesUtils.java

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesUtils {

    private static final String PROPERTIES_FILE_NAME = "application.properties";

    private static Properties properties;

    /**
     * Load properties file
     */
    static {
        properties = new Properties();
        try(InputStream inputStream = PropertiesUtils.class.getResourceAsStream(PROPERTIES_FILE_NAME)) {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Get property value and return it as a Double value.
     * @param key the property key.
     * @return the property value as a Double value.
     */
    public static Double getDouble(String key) {
        String value = properties.getProperty(key);
        try {
            return Double.valueOf(value);
        } catch (NumberFormatException e){
            return  0.0;
        }
    }

}

In the following example Java code, we learn how to use the PropertiesUtils.getDouble() static method above to read the property value as a Double value in Java program.

PropertiesUtilsExample.java

public class PropertiesUtilsExample {
    public static void main(String... args) {
        // Read Property Value as Double
        Double configValue = PropertiesUtils.getDouble("taxPercentage");

        System.out.println(configValue);
    }
}
The output as below.
0.1

Happy Coding 😊

Java Read Property Value as String

Java Read Property Value as Integer

Java Read Property Value as Long