msyql的FORMAT()函数设置小数位数,将小数位数保留到小数点后第n位,最后一位四舍五入

FORMAT()函数

  在mysql的查询中,如果我们输入的是小数类型,而保留几位小数因情况而变,我们可以用FORMAT()函数来设置想保留的几位小数。即将数据内容格式化,将数据格式化为整数或者带几位小数的浮点数(四舍五入)。

语法

SELECT FORMAT(a, b)
FROM table; 

其中,a为你要操作的字段,b为保留几位小数

举例理解

sql语句

创建表

create table formathanshu(
price DOUBLE not null primary key,
name varchar(20) not null
)charset=utf8;

加入数据:

insert into formathanshu  values(500.999,'The Journey to the West');
insert into formathanshu  values(4.6777,'The Dream of Red Mansion');
insert into formathanshu  values(99.999999,'The Water margin');
insert into formathanshu  values(33.3,'Romance of the Three Kingdoms');
insert into formathanshu  values(77.988,'Border town');

运行结果
在这里插入图片描述

要求

将price字段的所有数字保留两位小数
sql语句

SELECT name,FORMAT(price, 2) as '保留两位小数后的价格'
FROM formathanshu; 

运行结果
在这里插入图片描述
如果你想保留整数,那么将后面的数字设为0就OK啦!

猜你喜欢

转载自blog.csdn.net/hanhanwanghaha/article/details/106625785