mysql decimal round

£可爱£侵袭症+ 提交于 2019-12-12 12:29:59

问题


I'm new to mysql and need some basic things.

I need to round the decimals like :

21,4758 should be 21,48

0,2250 should be 0,22

23,0850 should be 23,08

22,9950 should be 22,99

I tried lots of thing but couldn't make it.

Thanks.


回答1:


DECLARE @old decimal(38, 10)
DECLARE @p decimal(38, 10)
SET @p = 21.4758

SET @p = @p * 100
SET @p = @p - 0.01
SET @p = ROUND(@p, 0)
SET @p = @p / 100.0
SELECT @p



回答2:


Try this:

// round the value to two decimal places 
SELECT ROUND(<YOUR_FIELD>, 2) field FROM <YOUR_TABLE>
// use truncate if you don't wan't to round the actual value
SELECT TRUNCATE(<YOUR_FIELD>, 2) field FROM <YOUR_TABLE>
// you can also use round or truncate depending whether the third decimal is > 5
SELECT IF(SUBSTR(<YOUR_FIELD>, 5, 1) > 5, 
   ROUND(<YOUR_FIELD>, 2), 
   TRUNCATE(<YOUR_FIELD>, 2)) field 
FROM <YOUR_TABLE>;

The above isn't a complete solution, but perhaps it will point you in the right direction.

Read the documentation for mysql round() and mysql truncate()



来源:https://stackoverflow.com/questions/13541650/mysql-decimal-round

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!