SQL货币汇率最接近0.05美分

时间:2016-09-05 11:57:37

标签: mysql math rounding

我正在尝试将MySQL SELECT中的钱花到最接近的0.05美分。

所以数字如:

140.70  should become 140.70
140.71  should become 140.70
140.72  should become 140.70
140.73  should become 140.75
140.74  should become 140.75
140.75  should become 140.75
140.76  should become 140.75
140.77  should become 140.75
140.78  should become 140.80
140.79  should become 140.80

更详细

0.00 = 0.00
0.01 = 0.00
0.02 = 0.00
0.022 = 0.00   // here the magic should happen 0.022 is closer to 0, so result is 0
0.023 = 0.05   // but 0.023 should be rounded to 0.05! cause first round 0.023 to 0.025 which should then be rounded up to 0.05
0.03 = 0.05

我已尝试使用MySQL CEIL()MySQL FLOOR()进行了一些不同的操作,但无法获得正确的结果。

创建了SQL Fiddle here

使用一个没有意义的表,除了我们需要一个SELECT来自:

CREATE TABLE hello ( world varchar(255) );
INSERT INTO hello (world) VALUES ('blubb');

这是选择查询:

SELECT 

 CEILING ( 0.05 / 0.05 ) * 0.05 AS CEIL_1,
 CEILING ( 0.06 / 0.05 ) * 0.05 AS CEIL_2,
 CEILING ( 0.07 / 0.05 ) * 0.05 AS CEIL_3,
 CEILING ( 0.08 / 0.05 ) * 0.05 AS CEIL_4,
 CEILING ( 0.09 / 0.05 ) * 0.05 AS CEIL_5

FROM hello;

这里的任何人都告诉我该怎么做?

1 个答案:

答案 0 :(得分:7)

SELECT ROUND(140.77/5,2) * 5;
+-----------------------+
| ROUND(140.77/5,2) * 5 |
+-----------------------+
|                140.75 |
+-----------------------+