How do I round number UP to the multiple of 10 in PostgreSQL easily?
Example:
In Out
100 --> 100
111 --> 120
123 --> 130
Sample data:
create table sample(mynumber numeric);
insert into sample values (100);
insert into sample values (111);
insert into sample values (123);
I can use:
select
mynumber,
case
when mynumber = round(mynumber,-1) then mynumber
else round(mynumber,-1) + 10 end as result
from
sample;
This works well, but looks ugly. Is there simpler way of doing this?
You can find SQLFiddle here
To round to the nearest tens, we mark the digits in the ones and tens column. The number 3596 has 6 in the ones column and 9 in the tens column. Since the digit in the ones column (i.e., 6) is between 5 and 9, we replace this digit with 0. We then increase the digit in the tens column (i.e., 9) by 1 and get 10.
Round to the nearest tenth means to write the given decimal number up to one decimal place. This is done in such a way that after rounding off, there is one digit after the decimal point.
You can use CEILING to round prices, times, instrument readings or any other numeric value. CEILING rounds up using the multiple supplied. You can use the MROUND function to round to the nearest multiple and the FLOOR function to round down to a multiple.
select ceil(a::numeric / 10) * 10
from (values (100), (111), (123)) s(a);
?column?
----------
100
120
130
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With