zoukankan      html  css  js  c++  java
  • 数据库中float类型字段,转化到前端显示,统一保留两位小数

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

  • 相关阅读:
    linux异步信号handle浅析
    数据库的基本操作增删改查
    POJ1789Truck History最小生成树两种做法(Kruskal+Prim)模板题
    POJ1113Wall求凸包周长
    POJ3565AntsKM变形
    HDU2150Pipe判断线段是否相交
    POJ1815Friendship最大流最小割点+拆点+枚举
    HDU3081 Marriage Match II 最大匹配+并查集+匈牙利算法
    POJ3348Cows求凸包面积
    HDU3277Marriage Match III并查集+二分+最大流
  • 原文地址:https://www.cnblogs.com/winv758241/p/7229615.html
Copyright © 2011-2022 走看看