Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Geetika .

Asked: November 23, 2016 - 6:05 pm UTC

Last updated: November 24, 2016 - 4:32 am UTC

Version: 11c

Viewed 1000+ times

You Asked

hi,

I am printing a number using below to_char format :

declare
var number(6,2)
begin
var := 65.2
dbms_output.put_line(to_char(var,'9999.99'));
end;

the above code prints ' 65.20' (3 spaces and the number).
one extra space is printed because positive value contain one extra space in to_char. I can not use FM because it will remove all the spaces(4 spaces) and my requirement is to print a number with length equals to the maximum length of number. If the length is less than the maximum length of number then add spaces up to the maximum length of number and print two digit after decimal.
I want to print ' 65.20'(2 spaces and number) from above code.
Please suggest.
Thanks!!

and Connor said...

SQL> declare
  2  var number(6,2);
  3  begin
  4  dbms_output.put_line('-------');
  5  var := 65.2;
  6  dbms_output.put_line(lpad(to_char(var,'FM9999.00'),7));
  7  var := 165.2;
  8  dbms_output.put_line(lpad(to_char(var,'FM9999.00'),7));
  9  var := 3165.2;
 10  dbms_output.put_line(lpad(to_char(var,'FM9999.00'),7));
 11  end;
 12  /
-------
  65.20
 165.20
3165.20

PL/SQL procedure successfully completed.


Adjust larger if you are including negatives as well

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

format string of to_char

Geetika Talreja, November 24, 2016 - 4:08 am UTC

could you please explain when we should use a 0 in format sting or a 9. How it makes a difference. sometimes both gives a same result.
For example to_char(12.3,'999.99') gives the same result as to_char(12.3,'999.00')
Connor McDonald
November 24, 2016 - 4:32 am UTC

Yes, but not always :-) depending on the formatting being done, eg

SQL> select
  2    to_char(12.3,'999.99') x1,
  3    to_char(12.3,'999.00') x2,
  4    to_char(12.3,'FM999.99') x3,
  5    to_char(12.3,'FM999.00') x4
  6  from dual;

X1      X2      X3      X4
------- ------- ------- -------
  12.30   12.30 12.3    12.30

1 row selected.


More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library