[Mysql]Decimal⽤法
⼀. mysql-Decimal理论说明:
1.⾸先,对于精度⽐较⾼的东西,⽐如money,我会⽤decimal类型,不会考虑float,double,因为他们容易产⽣误差,numeric和decimal 同义,numeric将⾃动转成decimal。
DECIMAL从MySQL 5.1引⼊,列的声明语法是DECIMAL(M,D)。在MySQL 5.1中,参量的取值范围如下:
M是数字的最⼤数(精度)。其范围为1~65(在较旧的MySQL版本中,允许的范围是1~254),M 的默认值是10。
D是⼩数点右侧数字的数⽬(标度)。其范围是0~30,但不得超过M。
说明:float占4个字节,double占8个字节,decimail(M,D)占M+2个字节。
如DECIMAL(5,2) 的最⼤值为9 9 9 9 . 9 9,因为有7 个字节可⽤。
M 与D 对DECIMAL(M, D) 取值范围的影响
类型说明取值范围(MySQL < 3.23)取值范围(MySQL >= 3.23)
MySQL < 3.23 MySQL >=3.23
DECIMAL(4, 1) -9.9 到 99.9 -999.9 到 9999.9
DECIMAL(5,1) -99.9 到 999.9 -9999.9 到 99999.9
DECIMAL(6,1) -999.9 到 9999.9 -99999.9 到 999999.9
DECIMAL(6,2) -99.99 到 999.99 -9999.99 到 99999.99
DECIMAL(6,3) -9.999 到 99.999 -999.999 到 9999.999
在MySQL 3.23 及以后的版本中,DECIMAL(M, D) 的取值范围等于早期版本中的DECIMAL(M + 2, D) 的取值范围。
结论:
当数值在其取值范围之内,⼩数位多了,则直接截断⼩数位。
若数值在其取值范围之外,则⽤最⼤(⼩)值对其填充。
⼆. JAVA+Mysql+JPA实践
msyql-Decimal对应java-BigDecimal
数据表定义
@Entity
public class TestEntity extends Model {
@Column(nullable = true, columnDefinition = "decimal(11,2)")
public BigDecimal price;
}
测试结果及说明
/**
* 1.mysql-Decimal(9+2,2)对应java-BigDecimal
* 2.整数部分9位,⼩数部分2位,⼩数四舍五⼊
* 3.整除部分超过限定位数9位,报错.
* 4.⼩数部分超过位数四舍五⼊截断,保留2位⼩数
*/
TestEntity entity = new TestEntity();
entity.price = new String(123456789.12d));
entity.save();
// 整数超过9位报错
/*
entity = new TestEntity();
entity.price = new String(1234567891.123d));
entity.save();
*/
entity = new TestEntity();
entity.price = new String(123456789.123d));
entity.save();
entity = new TestEntity();
entity.price = new String(123456789.126d));
entity.save();
entity = new TestEntity();
entity.price = new String(123456789d));
entity.save();
entity = new TestEntity();
entity.price = new String(123456.2355));
entity.save();bigdecimal取值范围
entity = new TestEntity();
entity.price = new String(123456.2356));
entity.save();
entity = TestEntity.find("price = ?",  new String(123456789.12d))).first();
System.out.println("查询结果:" + entity.id + ", " + entity.price);
插⼊结果
1  123456789.12
2  123456789.12
3  123456789.13
4  123456789.00
5  123456.24
6  123456.24