简体   繁体   中英

How to round up the number to tens (always up)

I come to you with a problem that I have spent almost two days on and I still cannot find a solution. I have a task that concerns mathematical calculations. I have a rule that you should always round the result up to tens (always up to the top). Examples: the result is 1 must be rounded to 10, the result is 2 must be rounded to 10, the result is 10, the result is 10, the result is 11 must be rounded to 20, the result is 99 must be rounded to 100, and so on. All of my example i tested at this page.

I know that we have three 'basic' functions for rounding. The first is the ceiling, which I would be interested in, but the ceiling does not always work the way I want it to. For example, for int value it is always this number, if it is 90 it will return 90, if it is 17 it will return 17 and so on. Code for this situation is below.

SELECT CEILING(91)

We also have a function that is used for rounding, but I cannot find the right parameters that will allow me to round a number up always. The positive maximum number is 1 and the rest of the z-directs my values. For example for 91 it will return 90 (with -1 param) and for 96 it will be 100 (with -1 param) but i want this 91 become 100.

SELECT ROUND(91, -1)

Thus, I wanted to try to do something with the floor, even doing some mathematical calculations, but in the long term, there are some mistakes. It will be work fork 91 (return 100) but for 90 it is still 100, when it should be 90.

SELECT FLOOR(90/10) * 10 + 10 AS RoundValue

Does anyone have any indication of how I could do this? Unfortunately, the compiler I use does not allow me to use the IF syntax at the beginning, the query must always start with select.

CEILING() looks like the right approach, but we need to work around integer division. This would seem to do what you want:

select val, ceiling(val / 10.0) * 10 as roundvalue
from (values (1), (10), (15), (90), (91), (95), (99)) t(val)

Yields :

val | roundvalue
--: | ---------:
  1 |         10
 10 |         10
 15 |         20
 90 |         90
 91 |        100
 95 |        100
 99 |        100

You can tweak the round function to get the desired value as follows:

select  round(val+4, -1) as roundvalue
from (values (1), (10), (15), (90), (91), (95), (99)) t(val)

DB<>Fiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM