MySQL数据类型-decimal(M,D)

看了一些博客,觉得很多互相矛盾,不如自己亲测一篇:
mysql 版本:8.0.13

select version(); --8.0.13

create table decimal_test(
	id int auto_increment PRIMARY key,
	score decimal(5,2)  -- 取值范围是 -999.99 到 999.99
);

-- 插入正数:
insert into decimal_test(score) VALUES(123); -- 123
insert into decimal_test(score) VALUES(0.1234); -- 0.12
insert into decimal_test(score) VALUES(1.23); -- 1.23
insert into decimal_test(score) VALUES(123.45); -- 123.45

--小数的位数可以大于d位。多出d位时会做四舍五入,截取到d位。
insert into decimal_test(score) VALUES(123.451); -- 123.45
insert into decimal_test(score) VALUES(123.455); -- 123.46
insert into decimal_test(score) VALUES(123.451123); -- 123.45
insert into decimal_test(score) VALUES(999.451123); -- 999.45
insert into decimal_test(score) VALUES(999.99123); -- 999.99

--整数的位数必须小于等于m-d,不然报错
insert into decimal_test(score) VALUES(12345.451123); -- Out of range value for column 'score' 
insert into decimal_test(score) VALUES(9999.451123); --  Out of range value for column 'score' 

--四舍五入之后正数部分大于m-d位了,报错
insert into decimal_test(score) VALUES(999.999); -- Out of range value for column 'score' 


-- 负数:符号不影响,所以其实和正数是一样用,就是多了一个负号
insert into decimal_test(score) VALUES(-1.234); -- -1.23
insert into decimal_test(score) VALUES(-12.34); -- -12.34
insert into decimal_test(score) VALUES(-123.45); -- -123.45
insert into decimal_test(score) VALUES(-999.45); -- -999.45
insert into decimal_test(score) VALUES(-999.99); -- -999.99
insert into decimal_test(score) VALUES(-1234); -- Out of range value for column 'score' 
insert into decimal_test(score) VALUES(-1234.99); -- Out of range value for column 'score'

总结:

  1. 整数的位数必须小于等于m-d,不然报错。小数的位数可以大于d位。多出d位时会做四舍五入,截取到d位。
  2. 以上均不包括小数点、符号的位数。数字的总长度是m位,保存后的小数位最多是d位。如果保存后是整数,小数位不会补0。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值