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啦!