客戶的一個需求,mybatis查詢到的數據庫的數據進行轉換,采用TypeHandler<T>的方式。float保留兩位精度可以采用DecimalFormat
直接貼上最終的解決代碼(事情沒有想象的簡單)
public class TwoDecimalFloatTypeHander implements TypeHandler<String> {
private static DecimalFormat decimalFormat=new DecimalFormat(".00");
public String getResult(ResultSet resultSet, String columnName) throws SQLException {
return decimalFormat.format(Double.parseDouble(resultSet.getString(columnName)));
}
public String getResult(ResultSet resultSet, int i) throws SQLException {
return decimalFormat.format(Double.parseDouble(resultSet.getString(i)));
}
public String getResult(CallableStatement callableStatement, int columnIndex)
throws SQLException {
return decimalFormat.format(Double.parseDouble(callableStatement.getString(columnIndex)));
}
public void setParameter(PreparedStatement ps, int i, String str,
JdbcType jdbcType) throws SQLException {
ps.setFloat(i,Float.parseFloat(str));
}
}
注意問題:
1. 采用ResultSet取數據庫中的float數據的時候,應該是resultSet.getFloat(...),但是這種取法會導致數字的精度發生變化【實際場景中:1071.88取出來后變成了1071.9】
解決:所以這里采用resultSet.getString(..)的方式來精確取值
2. 取值之后,DecimalFormat要求的輸入參數為數字,這時候要將上一步取到的數字轉換,但是不要轉換成float,不然又后變成1位小數,我采用double來轉換。
補充:如果要取的float字段為null,這樣寫就會報錯,所以建議加上判斷是否為空。(我的項目確定數字全部不為null)
