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)

  • 相关阅读:
    vb.net structure 定义静态数组
    调色板原理 & 编程
    CView::OnPreparePrinting
    MFC单文档程序架构解析
    基于Eclipse远程调试解决的预上线首页打开特别慢的问题
    Shiro Filter引发的思考
    Shiro Filter中利用Callable和Runnable的委派模式
    Shiro DefaultFilter
    防止Form表单重复提交的客户端及服务器端的方式
    Shiro Filter的设计概念
  • 原文地址:https://www.cnblogs.com/winv758241/p/7229615.html
Copyright © 2011-2022 走看看