首页 > 技术文章 > 数据库中float类型字段,转化到前端显示,统一保留两位小数

winv758241 2017-07-24 16:25 原文

客户的一个需求,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)

推荐阅读