You can combine numeric functions like this
SELECT
col,
ROUND(col / POWER(10,TRUNC(LOG(10, col)))) * POWER(10,TRUNC(LOG(10,col)))
FROM Data
See fiddle
Explanation:
LOG(10, number)
gets the power you need to raise 10 to in order get the number. E.g., LOG(10, 255) = 2.40654 and 10^2.40654 = 255
TRUNC(LOG(10, col))
the number of digit without the leading digit (2
).
POWER(10,TRUNC(LOG(10, col)))
converts, e.g., 255 to 100.
- Then we divide the number by this rounded number. E.g. for 255 we get 255 / 100 = 2.55.
- Then we round.
ROUND(2.55) = 3
- Finally we multiply this rounded result again by the previous divisor:
3 * 100 = 300
.
By using the Oracle ROUND function with a second parameter specifying the number of digits with a negative number of digits, we can simplify the select command (see fiddle)
SELECT
col,
ROUND(col, -TRUNC(LOG(10, col))) AS rounded
FROM Data
You can also use this to round by other fractions like quarters of the main number:
ROUND(4 * col, -TRUNC(LOG(10, col))) / 4 AS quarters
see fiddle