MySQL - 我如何总是四舍五入小数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7705548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:17:27  来源:igfitidea点击:

MySQL - How can I always round up decimals?

mysqlrounding

提问by quidpro

For instance I have the following value:

例如,我有以下价值:

0.000018

0.000018

This is 6 decimal places, but I want to round it up the nearest whole 4th decimal place, so that:

这是小数点后 6 位,但我想将其四舍五入到最接近的第 4 位小数,以便:

0.000018 -> 0.0001

0.000018 -> 0.0001

I've played with the round() funcction but if I simply use the round function:

我玩过 round() 函数,但如果我只是使用 round 函数:

round(0.000018,4) = 0.0000

round(0.000018,4) = 0.0000

When dealing with decimals for financial purposes, in this case one needs to round up and charge the customer instead of giving them a freebie! But round()will go round up or down depending on value, I need to consistently round up.

当出于财务目的处理小数时,在这种情况下,需要四舍五入并向客户收费,而不是给他们免费赠品!但是round()会根据价值向上或向下取整,我需要始终向上取整。

Is there a simple way of doing this?

有没有一种简单的方法可以做到这一点?

回答by Nanne

You can use ceil (ceiling). It only rounds up, so you'll have to multiply with 10000, do the ceil and then divide the result again.

您可以使用ceil (天花板)。它只会四舍五入,因此您必须乘以 10000,计算 ceil,然后再次除以结果。

So ceil(0.000145* 10000) = ceil(1.45) = 2Divide back and you'll have 0.0002

所以ceil(0.000145* 10000) = ceil(1.45) = 2划分回来,你就会有0.0002

EDIT: wait, wut? that doesn't work. I mean FLOORobviously but the working is the same :D The manual is on the same page too :)

编辑:等等,哇?那行不通。我的意思FLOOR很明显,但工作是一样的:D 手册也在同一页上:)

So floor(0.000145* 10000) = floor(1.45) = 1Divide back and you'll have 0.0001

所以floor(0.000145* 10000) = floor(1.45) = 1划分回来,你就会有0.0001

回答by Hyman Nord

There's another method, which is to add half a multiple of 10. For example: round(x+0.005, 2)where x is 0.923 = 0.93 which reduces the maximum floating point division error.

还有另一种方法,就是将 10 的倍数相加。例如:round(x+0.005, 2)其中 x 是 0.923 = 0.93,这样可以减少最大浮点除法误差。

回答by Saket

Use ROUND(X,D), which rounds the value X to D decimal places.

使用ROUND(X,D),将值 X 舍入到 D 小数位。