How to prevent Java from auto rounding up

egx :

I have a method which returns a double

public double getOdds() {
    return odds;
}

This works completly fine. However, the problem is when the data is displayed, it automatically rounds the inserted value up. I want to prevant that, and get a value with 2 decimals.

Here are my JSP where I call the method. The ArrayList "bets" consist of all values entered by the user. But, as explained above, when the user enters 2.75 then it will return 3.0

ArrayList <bets> bets = betsDAO.getBets(x, y);

for (bets bet : bets) {

    <td><%=bet.getOdds()%></td>
}

I'm still new to Java, and have tried looking for solutions, but unfortunatly I have not been able to solve the issue.

Andreas :

when the user enters 2.75 then it will return 3.0

The only reason for that to happen is if the value is limited to zero decimals at some point. Java only does that for int (or long or short or char or byte) values, and those are truncated, so result would be 2, not 3.0.

The only round-to-nearest I can envision is caused by the database or the JDBC driver:

  • The column type in the database is INTEGER or NUMBER(5,0) or something like that. Check your database schema.

  • The code reading the database (betsDAO) is calling getInt(...) and the JDBC driver rounds the value for you.

Anyway, the error is in code you haven't shown.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12504&siteId=1