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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章