How to get a float value from a JSON Object in Java

A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get and opt methods for accessing the values by name, and put methods for adding or replacing values by name.

In Java, you can import this class using import org.json.JSONObject. The objects of type JSONObject have a lot of useful methods to retrieve any of their values e.g getBoolean, getInt , getString , getDouble or getLong. Those methods return the value mapped by its name if it exists and convert them into the specific type (according to the name):

JSONObject myObject = new JSONObject("{ \"anyString\":\"Hello World\", \"aNumber\": 123, \"aDouble\": -895.25 }");

myObject.getString("anyString"); // Hello World
myObject.getNumber("aNumber"); // 123
myObject.getDouble("aDouble"); // -895.25

Pitifully, for float values (numbers with decimals) there's no such method as getFloat that returns the required type. If you're good with math and programming, you will be thinking that the getDouble function may would do the trick for you with a number like 12345678987.00 , however that would provide 1.2345678987E10 as result and with getLong you will be removing the decimals.

Retrieve float value from a JSON Object element

To achieve your goal of get an element from a JSON object in Float type, you can use the Big Decimal class. The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. The BigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, an exception is thrown; otherwise, calculations can be carried out to a chosen precision and rounding mode by supplying an appropriate MathContext object to the operation. In either case, eight rounding modes are provided for the control of rounding.

Import the BigDecimal class using the following statement in the top of your class:

import java.math.BigDecimal;

And then,all you need to do is to provide the double value (which returns an exponential value) from the element that you need of the JSON Object as first parameter to the BigDecimal.valueOf method and from the returned value, execute the floatValue method:

JSONObject myObject = new JSONObject("{ \"anyString\":\"Hello World\", \"aNumber\": 123, \"aDouble\": 12345678987.00 }");

float myFloatValue = BigDecimal.valueOf(myObject.getDouble("aDouble")).floatValue();

Happy coding !

Become a more social person