user3473132
user3473132

Reputation: 95

Confusing behavior of Division operator in PLSQL

I am a PLSQL statements to reverse a number.

and the code is this

declare
 num5 int:=54321;
 revnum int:=0;
 temp int;
 num int;
begin
 num:=num5;
 while(num5>0)
 loop
  temp:=mod(num5,10);
  num5:=num5/10;
  revnum:=revnum*10+temp;
 end loop;
dbms_output.put_line('Original number is '||num);
dbms_output.put_line('Reverse number is '||revnum);
end;
/ 

The output that I am getting is :

Original number is 54321

Reverse number is 123451

for me the code seemed alright, Why am i getting that extra '1'

To dig further i tried just dividing an number which is less than ten and still i am getting 1 instead of '0';

what is happening here?

Sample code that i tried out.

declare 
 num int:=6;
 res int;
begin
 res:=num/10;
 dbms_output.put_line(res);
end;
/

here also the output is 1 instead of 0. why is that?

Upvotes: 1

Views: 459

Answers (2)

wieseman
wieseman

Reputation: 176

I do understand your question if i say that you want to reverse a number (or string)? Thus 2468 becomes 8642. I think there is a another way to achieve this.

declare

  num5 int:=54321;
  revnum int:=0;
  temp int;
  num int;

  lv_num5       varchar2(100);
  ln_num5       number(3);
  lv_rev_num5   varchar2(100) := null;
  ln_rev_num5   number(3);

begin

  lv_num5 := to_char(num5);
  ln_num5 := length(lv_num5);

  for x in reverse 1..ln_num5   -- From the last digit to the first digit

    lv_rev_num5 := lv_rev_num5||substr(lv_num5, x, 1);

  end loop;

  ln_rev_num5 := to_number(lv_rev_num5);

  dbms_output.put_line('1- Original number is '||num5);
  -- Or
  dbms_output.put_line('2- Original number is '||lv_num5);
  dbms_output.put_line('Reverse number is '||ln_rev_num5);

end;
/ 

I hope that this solution also works for you.

Greetings Carlos

Upvotes: 0

Rob van Laarhoven
Rob van Laarhoven

Reputation: 8915

You are using integers. 6/10 is rounded to 1

declare 
 num1 number;
 num2 int;
begin
 num1 := 6/10;
 num2 := 6/10;
 dbms_output.put_line(num1);
dbms_output.put_line(num2);

end;
/

Results in

.6
1

You need a trunc around the num5/10. Otherwise the loop gets another cycle. (5/10) = .5 is rounded to 1.

declare
 num5 int:=715143212;
 revnum int:=0;
begin
 dbms_output.put_line('Original number is '||num5);
 while num5 > 0
 loop
    revnum := revnum * 10;
    revnum := revnum + mod(num5,10);
    num5 := trunc(num5/10);
 end loop;
dbms_output.put_line('Reverse number is  '||revnum);
end;
/ 

Upvotes: 2

Related Questions