加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

6、整型与浮点型

发布时间:2020-12-14 04:39:39 所属栏目:大数据 来源:网络整理
导读:1、数值型 整型 tinyint:占据空间1字节,储存范围-128——127,0——255 smallint:2个字节 mediuint:3个字节 Int:4个字节 bigint:8个字节 小数 浮点型:float(M,D) M叫“精度”---代表总位数,D叫“标度”,代表小数位(小数右边的位数) 定点型:decima

1、数值型

整型

tinyint:占据空间1字节,储存范围-128——127,0——255  
  smallint:2个字节    
  mediuint:3个字节  
  Int:4个字节  
  bigint:8个字节

小数

浮点型:float(M,D)   
M叫“精度”--->代表总位数,D叫“标度”,代表小数位(小数右边的位数) 

定点型:decimal(M,D)
长度不确定,是变长类型,把整数部分和小数部分,分开存储,比float精确。

1.1、学习tinyint的参数: (M) unsigned zerofill

unsigned

create table class(
    sname varchar(20) not null default ‘‘,age tinyint not null default 0
    )engine myisam charset utf8;
insert into class values (‘王五‘,128);
显示:1264 - Out of range value for column ‘age‘ at row 1

alter table class add score tinyint unsigned not null default 0;
insert into class(sname,score) values (‘张飞‘,-1);
显示:1264 - Out of range value for column ‘score‘ at row 1
  • 经过测试:age的默认范围是-128——127
  • int类型的数据,不加特殊说明,默认是有符号
  • 要想得到无符号修饰符,在后面添加unsigned

(M) 和 zerofill

zerofill zero是零,fill是填充,代表0填充
M必须和zerofill配合才有意义,M表示补0的宽度,表示位数不够的时候用0填充
zerofill默认是unsigned类型

alter table class add snum smallint(5) zerofill not null default 0;
insert into class (sname,snum) values (‘吕布‘,1);

使用navicat客户端,可能显示不出用0填充的现象
通过cmd命令行使用mysql客户端才能够显示

1.2、学习浮点型float的参数: (M,D)

create table salary(
sname varchar(20) not null default ‘‘,gongzi float(6,2)
)engine myisam charset utf8;

insert into salary values (‘张三‘,-9999.99);
insert into salary values (‘李四‘,9999.99);

insert into salary values (‘王2‘,9999.999);
显示:1264 - Out of range value for column ‘gongzi‘ at row 1

alter table salary add bonus float(5,2) unsigned not null default 0.00;

insert into salary (sname,bonus) values (‘王五‘,888.88);

1.3、学习定点型decimal的参数: (M,D)

create table account(
id int not null default 0,acc1 float(9,2) not null default 0.00,acc2 decimal(9,2) not null default 0.00
)engine myisam charset utf8;

insert into account
values 
(1,1234567.23,1234567.23);

mysql> select * from account;
+----+------------+------------+
| id | acc1       | acc2       |
+----+------------+------------+
|  1 | 1234567.25 | 1234567.23 |
+----+------------+------------+
1 row in set

通过上例可以看出float有时会损失精度,如果想银行账户这样的敏感字段,建议用decimal存储。
实际在银行使用整型存储,存的单位是分。

补充知识:

1、为什么有符号为tinyint的范围为:-128——127

计算机为了表示一个负数,会把最高位(左侧)的0/1,当成符号位来看,如为0,则是正数,1则是负数
0 0000000?
1 0000000
如果理解为+0,-0的话,则重复,浪费了一种存储的可能性,
为了解决这个问题,计算机采用补码的形式存储负数。
负数 = -(非符号位补码+1) = 绝对值位-128
1 2222211 --> -1
1 0000000 --> -128

2、浮点数占多大空间呢?

float能存10^38--10^(-38),如果M<=24,占4个字节,否则占8个字节。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读