mysql十进制轮

Can*_*Can 4 mysql truncate decimal rounding

我是mysql的新手,需要一些基本的东西.

我需要舍入小数,如:

21,4758应该是21,48

0,2250应该是0.22

23,0850应该是23,08

22,9950应该是22,99

我尝试了很多东西但是无法做到.

谢谢.

Cyc*_*ode 8

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>;
Run Code Online (Sandbox Code Playgroud)

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()


Ere*_*ren 7

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
Run Code Online (Sandbox Code Playgroud)