Working with numbers in PL/SQL (use numbers in PL/SQL)

Source: Internet
Author: User
Tags floor function oracle documentation

This article gives you all the information you need in order to begin working with numbers in your PL/SQL programs.

Numbers in PL/SQL

PL/SQL offers a variety of numeric datatypes to suit different purposes:

  • Number. A true decimal datatype that is ideal for working with monetary amounts. number is the only one of PL/SQL's numeric types to be implemented in a platform-independent fashion.

  • Pls_integer. Integer datatype conforming to your hardware's underlying integer representation. arithmetic is wrongly Med with your hardware's native machine instructions. You cannot store values of this type in tables; it is
    A pl/SQL-specific ype.

  • Simple_integer.introduced as of Oracle Database 11g Release 1. The simple_integer datatype results in significantly shorter execution times for natively compiled code. This datatype is not supplied ed in
    This article.

  • Binary_float and binary_double. single-and double-precision, IEEE-754, binary floating-point PES ypes. These binary PES ypes are highly specialized and are useful when you need to improve the performance of computation-intensive
    Operations. These datatypes are not supported ed in this article.

In practice, you may encounter other numeric types, such as float, integer, and decimal. These are subtypes of the four core numeric types in the preceding list.

Now let's take a closer look at number and pls_integer.

The number datatype. the number data-type is by far the most common numeric datatype you'll encounter in the world of Oracle and PL/SQL programming. use it to store integer, fixed-point, or floating-point numbers of just about
Any size. prior to Oracle Database 10g, number was the only numeric datatype supported directly by the Oracle database engine; now you can use binary_float and binary_double as well. number is implemented in a platform-independent manner,
And arithmetic on number values yields the same result no matter what hardware platform you run on.

To work with numbers in PL/SQL programs, you declare variables to hold the number values. The following declares a variable using the number datatype:

DECLARE   l_salary NUMBER; 

This range of values is demonstrated by the code block in Listing 1. (to_char and format masks are described later in this article .) such a declaration results in a floating-point number. oracle Database will allocate space for a maximum of 40 digits, and
Decimal point will float to best accommodate whatever values you assign to the variable. number variables can hold values as small as 10-130 (1.0e-130) and as large as 10126-1 (1.0e126-1 ). values smaller than 10-130 will get rounded down to 0, and calculations
Resulting in values larger than or equal to 10126 will be un-defined, causing runtime problems but not raising an exception.

Code listing 1: Demonstration of the range of number datatype values

DECLARE   tiny_nbr NUMBER := 1e-130;   test_nbr NUMBER;   --                              1111111111222222222233333333334   --                     1234567890123456789012345678901234567890   big_nbr      NUMBER := 9.999999999999999999999999999999999999999e125;   --                                 1111111111222222222233333333334444444   --                        1234567890123456789012345678901234567890123456   fmt_nbr VARCHAR2(50) := '9.99999999999999999999999999999999999999999EEEE';BEGIN   DBMS_OUTPUT.PUT_LINE(      'tiny_nbr          =' || TO_CHAR(tiny_nbr, '9.9999EEEE'));      /* NUMBERs that are too small round down to zero. */   test_nbr := tiny_nbr / 1.0001;   DBMS_OUTPUT.PUT_LINE(      'tiny made smaller =' || TO_CHAR(test_nbr, fmt_nbr));   /* NUMBERs that are too large throw an error: */   DBMS_OUTPUT.PUT_LINE(      'big_nbr           =' || TO_CHAR(big_nbr, fmt_nbr));   test_nbr := big_nbr * 1.0001;        -- too big   DBMS_OUTPUT.PUT_LINE(      'big made bigger   =' || TO_CHAR(test_nbr, fmt_nbr));END;And here is the output from this block:tiny_nbr          = 1.0000E-130tiny made smaller =   .00000000000000000000000000000000000000000E+00big_nbr           = 9.99999999999999999999999999999999999999900E+125big made bigger   =#################################################

If you try to explain icitly assign a number that is too large to your number variable, You'll raise a numeric overflow or underflow exception, but if you assign calculation results that exceed the largest legal value, no exception
Will be raised. if your application really needs to work with such large numbers, you will need to write validation routines that anticipate out-of-range values or consider using binary_double. using Binary datatypes has rounding implications, so be sure
Check the Oracle documentation on Binary PES ypes for details. for most uses, the chance of encountering these rounding errors will probably lead you to choose the number datatype.

Often when you declare a variable of type number, you will want to constrain its precision and scale, which you can do as follows:

NUMBER (precision, scale)

For example, I want to declare a variable to hold a monetary amount of up to $999,999 and that consists of dollars and cents (that is, just two digits to the right of the decimal point ). this declaration does the trick:

NUMBER (8,2)

Such a declaration results in a fixed-point number. the precision is the total number of significant digits in the number. the scale dictates the number of digits to the right (positive scale) or left (negative scale) of the decimal point and also
Affects the point at which rounding occurs. both the precision and scale values must be literal integer values; you cannot use variables or constants in the Declaration. legal values for precision range from 1 to 38, and legal values for scale range from-84
To 127.

When declaring fixed-point numbers, the value for scale is usually less than the value for precision.

The pls_integer datatype. The pls_integer datatype stores signed integers in the range of-2,147,483,648 through 2,147,483,647. Values are represented in your hardware platform's native integer format.

Here is an example of declaring a variable of Type pls_integer:

DECLARE   loop_counter PLS_INTEGER; 

The pls_integer datatype was designed for speed. when you perform arithmetic with pls_integer values, the Oracle software uses native machine arithmetic. as a result, it's faster to manipulate pls_integer values than it is to manipulate Integers
In the number datatype.

Consider using pls_integer whenever your program is compute-intensive and involves integer Arithmetic (and the values will never fall outside of this type's range of valid integers ). bear in mind, however, that if your use
Of pls_integer results in frequent conversions to and from the number type, you may be better off using number to begin. you'll gain the greatest efficiency when you use pls_integer for integer Arithmetic (and for loop counters) in cases in which you
Can avoid conversions back and forth with the number type.

Numeric built-in Functions

Oracle Database functions des an extensive set of built-in functions for manipulating numbers and for converting between numbers and strings. The following are some of the most commonly needed functions.

Round. the round function accepts a number and returns another number rounded to the specified number of places to the right of the decimal point. if you do not specify that number, round will return a number rounded to
Nearest integer.

Listing 2 events des some examples of callto round.

Code listing 2: callto round

BEGIN   DBMS_OUTPUT.put_line (ROUND (10.25));   DBMS_OUTPUT.put_line (ROUND (10.25, 1));   DBMS_OUTPUT.put_line (ROUND (10.23, 1));   DBMS_OUTPUT.put_line (ROUND (10.25, 2));   DBMS_OUTPUT.put_line (ROUND (10.25, -2));   DBMS_OUTPUT.put_line (ROUND (125, -2));END;And here is the output from this block:1010.310.210.250100

Note that a negative value for the second argument rounds to the nearest 10 (to the left of the decimal point ).

Trunc. trunc is similar to round, in that you can specify the number of digits to the right or left of the decimal point. the difference is that trunc simply removes or truncates digits. and, like round, you can specify a negative
Number, which truncates digits (makes them zero) to the left of the decimal point.

Listing 3 has des some examples of callto trunc.

Code listing 3: callto trunc

BEGIN   DBMS_OUTPUT.put_line (TRUNC (10.23, 1));   DBMS_OUTPUT.put_line (TRUNC (10.25, 1));   DBMS_OUTPUT.put_line (TRUNC (10.27, 1));   DBMS_OUTPUT.put_line (TRUNC (123.456, -1));   DBMS_OUTPUT.put_line (TRUNC (123.456, -2));END;And here is the output from this block:10.210.210.2120100

Floor and Ceil. The floor function returns the largest integer equal to or less than the specified number.

The Ceil function returns the smallest integer equal to or greater than the specified number.

The following block and its output demonstrate these two functions:

BEGIN   DBMS_OUTPUT.put_line (FLOOR (1.5));   DBMS_OUTPUT.put_line (CEIL (1.5));END;/12

MoD and remainder. Mod and remainder both return the remainder of one number divided by another, but that remainder is calculated differently for each function.

The formula used by Oracle database for MOD is

MOD (m, n) = m - n * FLOOR (m/n)

When both M and N have the same sign (positive or negative). If the signs of M and N are different, then the formula used is:

MOD (m,n) = ( m - n * CEIL(m/n) )

Whereas the formula used for remainder is

n2 - (n1*N)

Where n1 is not zero and where N is the integer nearest N2/N1. if N2/N1 equals X.5, then n is the nearest even integer.

Listing 4 primary des a block that demonstrates the effect of and differences between these two functions.

Code Listing 4: callto mod and remainder

BEGIN   DBMS_OUTPUT.put_line (MOD (15, 4));   DBMS_OUTPUT.put_line (REMAINDER (15, 4));   DBMS_OUTPUT.put_line (MOD (15, 6));   DBMS_OUTPUT.put_line (REMAINDER (15, 6));END;/

And here is the output from this block:

3-133

To_char. use to_char to convert a number to a string. in its simplest form, you pass a single argument (the number) to to_char and it returns the string representation of that number, exactly long enough to contain all of its
Significant digits.

Listing 5 primary des a block that shows some to_char examples. As you can see, leading and trailing zeros are not in the string representation of the number.

Code listing 5: callto to_char

BEGIN   DBMS_OUTPUT.put_line (TO_CHAR (100.55));   DBMS_OUTPUT.put_line (TO_CHAR (000100.5500));   DBMS_OUTPUT.put_line (TO_CHAR (10000.00));END;

And here is the output from this block:

100.55 100.55 10000

To specify a format for the string to which the number is converted, provide as the second argument to to_char a string that contains a combination of special format elements. suppose, for example, that I want to display large
Numbers with a "1000s" delimiter. in other words, I want to display "10,000" instead of "10000" so I wocould use the following format: often, when you have to convert a number to a string, you need that number to fit a certain format. you might, for example,
Want to display the number as a currency, so that even if there are no cents, you need to include the ". 00 "-in such cases, you will need to add a second argument in your call to to_char: The format mask.

BEGIN   DBMS_OUTPUT.put_line (      'Amount='||      TO_CHAR (        10000      , '9G999G999'));END;

The G element indicates where in the string I wocould like to place the group separator. (the character used for the separator is determined by the national language settings database parameter nls_numeric_characters .) the 9 element tells Oracle Database
To put a significant digit or a blank space in that location. As a result, the output from this block is

Amount=    10,000

If I want to have zeros appear instead of blanks, I can use 0 instead of 9, as in

BEGIN   DBMS_OUTPUT.put_line (      'Amount=' ||      TO_CHAR (         10000       , '0G000G999'));END;Amount= 0,010,000

If I do not want any leading zeros, extra blks, or white space appearing in my converted number, I will use the FM element, as in

BEGIN   DBMS_OUTPUT.put_line (      'Amount=' ||      TO_CHAR (         10000      , 'FM9G999G999'));END;Amount=10,000

Suppose that my number is actually a monetary unit consisting of dollars (or euros) and cents and I want to show the currency symbol as well as the cents portion. I can use the following format:

BEGIN   DBMS_OUTPUT.put_line (     'Salary=' ||     TO_CHAR (        14500.77     , 'FML999G999D99'));END;Salary=$14,500.77

The L element specifies the location of the local currency symbol (such as $ or €) in the return value (the nls_currency parameter specifies the local currency symbol ). the D element indicates the location of the decimal point. (The character used
For the decimal point is specified by the database parameter nls_numeric_characters .)

It is outside the scope of this article to explain all of the specified elements available for use in number formats (there are, for example, at least four elements just for denoting monetary units ). check Oracle
Database SQL Language Reference 11g Release 2 (11.2), for a complete description.

------------------------------

Present by Dylan.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.