码迷,mamicode.com
首页 > 其他好文 > 详细

浮点数与定点

时间:2014-06-16 16:43:09      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:mysql

  1. 浮点数

    说明:小数点左边,能大到多少?

          小数点右边,又能大到多少?

    小数型

        float(M),decimal(M,D)

        M叫“精度”---->代表总位数(不包含点),而D是标度,代表小数位(小数右边的位数)

    例:

        float(6,2)    ------> -999999.99到9999.99  

        在该例子中6是M(精度)2是D(标度)

    

    mysql> create table salary( 

    mysql> sname varchar(30) not null default ‘‘,

    mysql> gongzi float(6,2)

    mysql> )engine myisam charset utf8;

    

    mysql> inset into salary values (‘zhangsan‘,-3200.78),(‘lisi‘,720.3);

    msyql> select * from salary;

    

    +----------+----------+

    | sname    | gongzi   |

    +----------+----------+

    | zhangsan | -3200.78 |

    | lisi     |   720.30 |

    +----------+----------+

    插入一个奖金列

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

    mysql> insert into selary (sname,bonus) values (‘zhaoliu‘,784.32);

    mysql> select * from salary;

    +----------+----------+--------+

    | sname    | gongzi   | bonus  |

    +----------+----------+--------+

    | zhangsan | -3200.78 |   0.00 |

    | lisi     |   720.30 |   0.00 |

    | zhaoliu  |     NULL | 784.32 |

    +----------+----------+--------+

    

    bonsu加了unsigned类型,不能为负


    用来表示数据中的小数,除了float---浮点

    还有一种叫定点,decimal定点是把整数部分和小数部分,分开存储

    比float精确

    下面建一个账户的表来验证float与decimal的区别

    mysql> create table account(

    mysql> id int not null default 0,

    mysql> acc1 float(9,2) not null default 0.00,

    mysql> acc2 decimal(9,2) not null default 0.00

    mysql> )engine myisam charset utf8;

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

    mysql> select * from account;

    +----+------------+------------+

    | id | acc1       | acc2       |

    +----+------------+------------+

    |  1 | 1234567.25 | 1234567.23 |

    +----+------------+------------+

    我们会发现这两个数字后面的小数会不一样

    通过上例可以看出float有时会损失精度,

    如果像账户这样敏感的字段,建议用decimal

    

    mysql> insert into account values (2,1234567.24,17894561.23);

    mysql> select * from account;

    +----+------------+------------+

    | id | acc1       | acc2       |

    +----+------------+------------+

    |  1 | 1234567.25 | 1234567.23 |

    |  2 | 1234567.25 | 9999999.99 |

    +----+------------+------------+

    出现上面这种情况是因为我们acc2定义的数字超过了decimal这个类型的最大值


本文出自 “不变的时光” 博客,转载请与作者联系!

浮点数与定点,布布扣,bubuko.com

浮点数与定点

标签:mysql

原文地址:http://shansongxian.blog.51cto.com/5040181/1426640

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!