简体   繁体   中英

Round to 0.5 in sql

I have number data:

123.42
12.54
1.02
2.99

For each one I want to obtain the closest number to a 0.5 step. So

func(123.42)=123.0
func(12.54)=12.5
func(1.02)=1.0
func(2.99)=2.5

Any clues? I'm trying with a trunc((x-floor(x))*5)/5) but can't get anything.

val := round(val*2) / 2;

Such expresion should be what you described in question. So function is:

create or replace function func(val number) return number
is
begin 
  return round(val*2) / 2;
end;

But looking on examples you don't want closest number but highest number smaller than your value rounded to 0.5. And this you will obtain with:

create or replace function func(val number) return number
is
begin 
  return floor(val*2) / 2;
end;

If you would like the smallest number greater than value rounded to 0.5 it would be:

create or replace function func(val number) return number
is
begin 
  return ceil(val*2) / 2;
end;

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