MySQL中支持浮点数的类型有FLOAT、DOUBLE和DECIMAL类型,DECIMAL 类型不同于FLOAT和DOUBLE,DECIMAL 实际是以串存放的。DECIMAL 可能的最大取值范围与DOUBLE 一样,但是其有效的取值范围由M 和D 的值决定。如果改变M 而固定D,则其取值范围将随M 的变大而变大。

对于精度比较高的东西,比如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) 的最大值为9999.99,因为有7 个字节可用。

所以M 与D 是影响DECIMAL(M, D) 取值范围的关键

类型说明 取值范围(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

给定的DECIMAL 类型的取值范围取决于MySQL数据类型的版本。对于MySQL3.23 以前的版本,DECIMAL(M, D) 列的每个值占用M 字节,而符号(如果需要)和小数点包括在M 字节中。因此,类型为DECIMAL(5, 2) 的列,其取值范围为-9.99 到99.99,因为它们覆盖了所有可能的5 个字符的值。

# 在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 BigDecimal(Double.toString(123456789.12d));

entity.save();

// 整数超过9位报错

/*

entity = new TestEntity();

entity.price = new BigDecimal(Double.toString(1234567891.123d));

entity.save();

*/

entity = new TestEntity();

entity.price = new BigDecimal(Double.toString(123456789.123d));

entity.save();

entity = new TestEntity();

entity.price = new BigDecimal(Double.toString(123456789.126d));

entity.save();

entity = new TestEntity();

entity.price = new BigDecimal(Double.toString(123456789d));

entity.save();

entity = new TestEntity();

entity.price = new BigDecimal(Double.toString(123456.2355));

entity.save();

entity = new TestEntity();

entity.price = new BigDecimal(Double.toString(123456.2356));

entity.save();

entity = TestEntity.find("price = ?", new BigDecimal(Double.toString(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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐