类型转换是我们日常开发中经常会遇到的一个需求,最近在将浮点型转换成字符型的时候就遇到了一个问题,所以总结分享出来,下面这篇文章主要给大家介绍了mysql中关于浮点型转字符型可能遇到的问题的相关资料,需要的朋友可以参考下。
前言
本文主要给大家介绍了mysql中在将浮点型转字符型的时候遇到的一个问题,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
一 问题描述
今天遇到一个刷数据的需求,是修改产品的重量(字段类型为float),修改了产品的重量之后,是需要记录到日志表中的(字段类型为varchar),表结构如下:
临时刷数据表:
create table `temp_170830` (
`id` int(10) unsigned not null auto_increment comment '主键id',
`goods_sn` varchar(255) not null default '' comment '产品编码',
`goods_weight` float(9,4) not null default '0.0000' comment '产品重量',
`actual_weight` float(9,4) not null default '0.0000' comment '实际重量',
`new_actual_weight` float(9,4) not null default '0.0000' comment '新的实际重量',
`create_user` varchar(30) not null default '' comment '创建人',
primary key (`id`),
key `idx_goods_sn` (`goods_sn`)
) engine=innodb auto_increment=8192 default charset=utf8 comment='临时刷重量表';
日志表:
create table `log_weight` (
`id` int(10) unsigned not null auto_increment comment '主键id',
`goods_sn` varchar(50) not null default '' comment '产品编码',
`which_col` varchar(100) not null default '' comment '修改字段',
`old_value` varchar(50) not null default '0.00' comment '更新前值',
`new_value` varchar(50) not null default '0.00' comment '更新后值',
`update_user` varchar(100) not null default '' comment '创建人',
`update_time` datetime not null default current_timestamp on update current_timestamp,
`wh_update_time` timestamp not null default current_timestamp on update current_timestamp comment '记录修改时间',
primary key (`id`),
key `idx_goods_sn` (`goods_sn`),
key `idx_update_user` (`update_user`),
key `wh_update_time` (`wh_update_time`)
) engine=innodb auto_increment=14601620 default charset=utf8 comment='重量修改日志';
如上面建的表所示,我需要将temp_170830表的actual_weight和new_actual_weight字段分别刷入log_weight表的old_value和new_value字段,sql语句如下:
insert into log_weight(goods_sn, which_col, old_value, new_value, update_user)
select goods_sn,'actual_weight',actual_weight,new_actual_weight,create_user from temp_170830;
本来以为到这里就已经大功告成了,毕竟只是插入一些日志记录,后来为了简单的进行核对,发现数据有些不对劲,如下图所示:
临时表数据截图:
日志表数据截图:
对比可以发现,插入的日志记录数据无缘无故后面多了很多位的小数,不知道从哪里冒出来的,后来一想,可能是本来浮点型的数据就是除不尽的,转成varchar的时候就把后面的那些也给带出来了,暂时也不是很确定,后续确定之后再补充,然后自己临时找了一个转varchar的方法concat,调整如下:
insert into log_weight(goods_sn, which_col, old_value, new_value, update_user)
select goods_sn,'actual_weight',concat(actual_weight,''),concat(new_actual_weight,''),create_user from temp_170830;
顺利解决日志记录问题。
总结如下:
1 在记录价格和重量数字字段的时候,尽量不要使用浮点型!!!,浮点数坑多(比如浮点型是不能判断相等的!!!),最好是采用int整型,业务上要显示小数时,读取出来再除以相应的位数,比如99.98元,应存储9998,读取出来时,用9998/100来显示。
2 在float转varchar时,应该先把float用concat函数先转成varchar,再存储入varchar字段。
以上就是mysql中关于浮点型转换成字符型出现的一些问题解决的详细内容。