Search code examples
javacastingdoublebigdecimal

Convert BigDecimal Object to double value


I am querying a database with a jdbc connection:

    List<Map<String, Object>> rows = jdbcTemplate.queryForList(SELECT_QUERY);   
    for(Map row : rows) {
        Results result = new Results();
        result.setResultValueDouble((Double)row.get("AMOUNT"));

        //add the data object to the list
        resultList.add(result);
    }

However, the object I query is in BigDecimal and I would like to convert it to plain double. Using a cast does not work and gives me a ClassCastException.

Any recommendations how to cast this Object properly?

I appreciate your reply!


Solution

  • result.setResultValueDouble(((BigDecimal)row.get("AMOUNT")).doubleValue());
    

    A cast on an object doesn't change the type of the object, only the type of the expression you use to refer to it, so it can't convert a BigDecimal to a Double, since a BigDecimal isn't a Double. Instead, call the doubleValue() method of the BigDecimal.