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)

  • 相关阅读:
    为什么需要Docker?
    一分钟学会《模板方法模式》
    2018再见|2019你好
    三分钟学会《门面模式》
    策略模式原来这么简单!
    外行人都能看得懂的机器学习,错过了血亏!
    我是如何将博客转成PDF的
    面试前必须知道的MySQL命令【explain】
    count(*)、count(1)和count(列名)的区别
    Linux shell去除字符串中所有空格
  • 原文地址:https://www.cnblogs.com/winv758241/p/7229615.html
Copyright © 2011-2022 走看看