• 数据库中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)

  • 相关阅读:
    esp8266(3) Arduino通过ESP8266连接和获取网站源代码
    esp8266(2) 智能配置
    图像工程考试
    Arduino IDE for ESP8266 ()esp8266项目 WIFI攻击器
    esp8266(1) 手机+Arduino+esp8266通信
    esp8266(0) AT指令
    ROS ZED
    手机APP
    Arduino IDE for ESP8266教程(0)配置IDE
    Arduino 433 + 串口
  • 原文地址:https://www.cnblogs.com/winv758241/p/7229615.html
Copyright © 2020-2023  润新知