Yielding the desired number of decimal places using the AVG function in t-sql

Hello again.  Confused retired hobby coder having trouble setting up a scalar-valued function to return the desired number of decimal places from a AVG query.
Whenever I run the following script I get the number of decimals I desire:
Using the above I created a scalar-valued function as follows:
Running this function as: SELECT [dbo].[TestHCIPartial] (1,3)  my return is -7.
Can you help me with the function causing it to yield the answer to 6 decimal places?
Thanks and regards, Minuend.

You've not specified precision and scale in UDF return type. So you're leaving it to server to interpret it based on default settings
If you want exactly up to four decimal places tweak udf as below
ALTER FUNCTION..
RETURNS decimal(20,4)
AS
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page

Similar Messages

  • Determine Number of Decimal Place using BigDecimal

    I was interested to have the following getNumberOfDecimalPlace function :
    System.out.println("0 = " + Utils.getNumberOfDecimalPlace(0)); // 0
    System.out.println("1.0 = " + Utils.getNumberOfDecimalPlace(1.0)); // 0
    System.out.println("1.01 = " + Utils.getNumberOfDecimalPlace(1.01)); // 2
    System.out.println("1.012 = " + Utils.getNumberOfDecimalPlace(1.012)); // 3
    System.out.println("0.01 = " + Utils.getNumberOfDecimalPlace(0.01)); // 2
    System.out.println("0.012 = " + Utils.getNumberOfDecimalPlace(0.012)); // 3
    I use the following code
        public static int getNumberOfDecimalPlace(double value) {
            final BigDecimal bigDecimal = new BigDecimal("" + value);
            final String s = bigDecimal.toPlainString();
            System.out.println(s);
            final int index = s.indexOf('.');
            if (index < 0) {
                return 0;
            return s.length() - 1 - index;
        }However, for case 0, 1.0, it doesn't work well. I expect, "0" as result. But they turned out to be "0.0" and "1.0". This will return "1" as result.
    0.0
    0 = 1
    1.0
    1.0 = 1
    1.01
    1.01 = 2
    1.012
    1.012 = 3
    0.01
    0.01 = 2
    0.012
    0.012 = 3
    Any solution?

    Please [don't cross-post!|http://stackoverflow.com/questions/2296110/determine-number-of-decimal-place-using-bigdecimal], it's considered rude. If you must do it, then at least link each post so that people can find out which answers you've already got in order to avoid duplicate work on our part.
    Please read [_How To Ask Questions The Smart Way_|http://www.catb.org/~esr/faqs/smart-questions.html].

  • Can not change the number of decimal places in the normalization of result

    dear all
        i want to see the proportion of some data, for example, the income of May is 300, and the total income is 1000, i need to display it like 33.33% . so i set the
    Calculate single values as normalization of result, and then it display 33.333%, i like to display only two number of decimal places, so i set the number of decimal places as 0.00, but i doesn't work, it still display three decimal numbers.
        maybe you say i can use the percentage function like %CT %GT %RT, but i need to allow external access to my query, so the i can not use those functions.
        can somebody helps me ? your advice is appreciated.

    hi,thanks for your advice, but that doesn't suit for my problem.
    before i set the normalization of result, i can change the decimal values. After that i cann't.
    In your thread, someone proposes use the T-code OY04. but this wouldn't help. As i change to other key figure, such as user quantity, when i set normalization of result, it still display 3 decimal values.
    i think the point maybe lie in the normalization of result. please advise... thanks...

  • How to get the number of decimal places configured for a site column

    Hi,
    I have a column 'SampleNumCol' of type Number, the number of decimal places to be displayed is configured as 2.
    The column conatins a value, but when retrieved programatically is displayed as 5.00000000  instead of 5.00.
    I am retrieving this column using listitem.Properties[field.InternalName].
    I need to trim the decimals based on  number of decimal places configured for the site column.
    How to get the number of decimal places configured for a site column?
    Thanks in advance,
    dhijit

    Get the field as SPFieldNumber and then check DisplayFormat which returns
    SPNumberFormatTypes
    SPFieldNumber numberField = list.Fields.GetFieldByInternalName("YourNumberFieldName") as SPFieldNumber;
    SPNumberFormatTypes numFormatType = numberField.DisplayFormat;

  • How to set the number of decimal places.

    Just wondering what and where the code would be to set the number of decimal places when calculating an answer.

    Depending on exactly what result you want you could alternatively format the result to a set number of decimal places.
    This is not so good for financial applications where they want the total of 10 transactions to match the total of each number displayed but can be kind of important for scientific ones.
    eg
    someNumber.ToString("N3"));
    Gives you three decimal places without changing the someNumber.
    If this turned out to be wpf then you have stringformat you can use on a binding.
    Hope that helps.
    Recent Technet articles:
    Property List Editing ;  
    Dynamic XAML

  • Altering number of decimal places of formatted number

    Using http://java.sun.com/docs/books/tutorial/i18n/format/numberFormat.html I have worked out how to format a number, almost. When I follow the example in this tutorial that shows how format a double, it always rounds it to 3 decimal places. How do I alter the number of decimal places that this formatting procedure outputs? I used the US as the locale and English as the language. I am assuming that if these parameters are chosen, 3 decimal places is the output. Is this assumption correct?

    Look at the next chapter :)
    http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html

  • Bex: overall Result: number of decimal places

    Good day
    How to I change the number of decimal places for the "Overall result" in a query?
    Your assistance is appreciated.
    Cj Faurie

    Thanks for your response.
    The number format in properties for the KF (formula created in query) has been set to '0' decimal places. I also use the "Average of all values <>0" in the calculate results for the KF. If you use "Summation" then the decimal will apply, but not with the "Average .....".
    My "0CALMONTH" is in rows and results is based on this (set to 'never') as I want the Overall Result to display first as my chart is based on the OResult and not the individual figures.
    "This is the layout of my report"
    Territory     Overall Result    2007/02     2007/03    2007/03
    Boland       205.8333           21             242          355
    The "overall result' should display as '206'. Why does the 'decimal place' not apply to "Average of all v...."?
    Thanks
    Cj

  • BEx Analyzer displays wrong number of decimal places after implementing BW patch

    Hey folks,
    we patched our BW 7.31 from PL10 to PL15 last weekend and now we got some issue with the number of decimal places shown in BEx Analyzer 7.x.
    One example for KF X
    Settings Info Object X
    Decimal Places:                         Not defined
    RSRT - Display X
    Shows 3 decimal places
    Query Designer Settings using KF X
    Number of Descimal Places:     0  [Use Default Settings: NO]
    BEx Analyzer Properties for KF X
    Decimal Places:                         0
    Resulting in BEx Analyzer workbook shows 3 decimal places instead of 0!
    Anyone with an good idea about that?
    Thanks,
    Andreas

    Hi Andreas,
    Have you used the list calulation like "Calculate Result As Average" or "Calculate Single Values as normalization of result" in the relevant key figures?
    For "Calculate Single Values as normalization of result",iIt is the known design that it is always displayed with three decimal places for normalized values, and the setting in Query Designer for
    decimal place doesn't take effect.
    For "Calculate Result As Average", the following note maybe relevant.
    2096911 - Decimal places in query result is wrong, if average is used and display precision is set to less than 3, it will always show 3 decimal places.
    Another clue is to check if the key figure is a Quantity type with unit, and what's defined in table
    T006 field ANDEC for this unit.
    Hope this helpful.
    Regards,
    Ceciclia

  • Round a double value to a specific number of decimal places?

    Hello,
    Is there standard java function which will round a double value to a specified number of decimal places? Something like:
    double d = 4.34523;
    d = round(d, 2);
    where d is finally assigned the value of 4.34?
    Thanks!
    -exits

    No, because doubles hold values in binary (as do all values in a computer, of course, but there's no additional stuff to indicate decimal values).
    If you want values with specific rounding rules in decimal, use java.math.BigDecimal.
    If you just want to format the number with a specified number of decimal digits, use java.text.DecimalNumber.

  • Use of ROW_NUMBER() function in PL/SQL

    I have a Table Emp with the following Structure
    SQL> desc emp
    Name Null? Type
    EMPNO NUMBER(2)
    ENAME VARCHAR2(50)
    HIREDATE DATE
    DEPTNO NUMBER(2)
    If I write a following query on this table
    SQL> SELECT deptno, hiredate, record_id
    2 FROM (SELECT deptno, ename, hiredate, ROW_NUMBER()
    3 OVER (ORDER BY hiredate) AS record_id
    4 FROM emp)
    5 WHERE record_id >= 2
    6 AND record_id <=5;
    The Result I get is
    DEPTNO HIREDATE RECORD_ID
    10 22-NOV-01 2
    10 22-NOV-01 3
    10 22-NOV-01 4
    10 22-NOV-01 5
    But if I put this query in a cursor in a PL/SQL block. The
    pl/sql does not compiles and gives me the following address
    SQL> DECLARE
    2 CURSOR c_my IS
    3 SELECT deptno, hiredate, record_id
    4 FROM (SELECT deptno, ename, hiredate, ROW_NUMBER()
    5 OVER (ORDER BY hiredate) AS record_id
    6 FROM emp)
    7 WHERE record_id >= 2
    8 AND record_id <=5;
    9 BEGIN
    10 FOR c_rec IN c_my LOOP
    11 dbms_output.put_line(c_rec.ename);
    12 END LOOP;
    13 END;
    14 /
    OVER (ORDER BY hiredate) AS record_id
    ERROR at line 5:
    ORA-06550: line 5, column 13:
    PLS-00103: Encountered the symbol "(" when expecting one of the
    following:
    , from
    Question: Can you please tell me how I can use the ROW_NUMBER()
    function in PL/SQL. I need to use this for selecting the correct
    range of records for Pagination on a website.
    Thanks in advance
    Prashant

    As Andrew said, PL/SQL hasn't caught up with the newer bits of
    SQL.  I have heard that in 9i, they will be the same, but in 8i
    there are still things that you can do in SQL that you cannot do
    directly in PL/SQL, such as the new functions like ROW_NUMBER. 
    However, you can use NDS as a work around.  The following does
    the same as what you posted:
    SET SERVEROUTPUT ON
    DECLARE
      TYPE c_my_type  IS REF CURSOR;
      c_my               c_my_type;
      TYPE c_rec_type IS RECORD
        (deptno          emp.deptno%TYPE,
         ename           emp.ename%TYPE,
         hiredate        emp.hiredate%TYPE,
         record_id       INTEGER);
      c_rec              c_rec_type;
      v_sql              VARCHAR2 (4000);
    BEGIN
      v_sql :=
      'SELECT deptno, ename, hiredate, record_id
       FROM   (SELECT deptno, ename, hiredate,
                      ROW_NUMBER() OVER
                        (ORDER BY hiredate)
                        AS record_id
              FROM    emp)
       WHERE  record_id >= 2
       AND    record_id <= 5';
      OPEN c_my FOR v_sql;
      LOOP
        FETCH c_my INTO c_rec;
        EXIT WHEN c_my%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE (c_rec.ename);
      END LOOP;
    END;
    However, you stated that you need it for selecting the correct
    range of records for pagination on a website.  For that, you
    will want something more like this:
    CREATE OR REPLACE PACKAGE package_name
    AS
      TYPE c_my_type     IS     REF cursor;
      PROCEDURE procedure_name
        (c_my            IN OUT c_my_type,
         p_record_id1    IN     NUMBER DEFAULT 1,
         p_record_id2    IN     NUMBER DEFAULT 4);
    END package_name;
    CREATE OR REPLACE PACKAGE BODY package_name
    AS
      PROCEDURE procedure_name
        (c_my            IN OUT c_my_type,
         p_record_id1    IN     NUMBER DEFAULT 1,
         p_record_id2    IN     NUMBER DEFAULT 4)
      IS
        v_sql                   VARCHAR2 (4000);
      BEGIN
        v_sql :=
            'SELECT deptno, ename, hiredate, record_id'
        || ' FROM   (SELECT deptno, ename, hiredate,'
        ||                ' ROW_NUMBER() OVER'
        ||                  ' (ORDER BY hiredate)'
        ||                  ' AS record_id'
        || ' FROM    emp)'
        || ' WHERE  record_id >= :a'
        || ' AND    record_id <= :b';
        OPEN c_my FOR v_sql
        USING p_record_id1, p_record_id2;   
      END procedure_name;
    END package_name;

  • Changing number of decimal places for Unit of Measure

    Hi All,
    I have a requirement to convert a quantity in one unit of measure to another (custom) unit of measure.
    The issue is that the custom unit of measure has 4 decimal places (customer requirement). I found function module MD_CONVERT_MATERIAL_UNIT which does the trick for regular, 3 decimal places, UoM's. It won't output 4 decimal places since the output data type is EKPO-MENGE, which has 3 decimal places.
    Does anyone have experience with trying to convert material's UoMs into 4 or more decimal places?
    Thanks!

    <b>round_f_to_15_decs</b>  round variable of type f to 15 decimals
    Sometimes type F (float) is used to represent exact data (Amounts, Quantities):
    if values are to big to be represented as Packed (> 31 decimals)
    to significally improve performance of calculations, e.g. in statistical reports
    G_DECIMAL_PLACES_GET
    REPORT Z_ROUNDING .
    DATA: float TYPE f,
          amount TYPE p DECIMALS 2,
          correctamount TYPE p DECIMALS 2,
          chars(5) TYPE c value '1.005'.
    CLASS cl_abap_math DEFINITION LOAD.
    correctamount = chars.
    WRITE: / 'Exactly:', chars,
           / 'Correct Amount:',  correctamount.
    float = chars.
    amount = float.
    skip 2.
    WRITE: / '==== Usual Processing:',
           / 'Float:', float,
           / 'Decimals 3:', float DECIMALS 3,
           / 'Decimals 2:', float DECIMALS 2,
           / 'Amount:',  amount.
    float = cl_abap_math=>round_f_to_15_decs( float ).
    amount = float.
    skip 2.
    WRITE: / '==== Correct Processing:',
           / 'Float:', float,
           / 'Decimals 3:', float DECIMALS 3,
           / 'Decimals 2:', float DECIMALS 2,
           / 'Amount:',  amount.

  • How to display 2 decimal places using DecimalFormat?

    Hi, i would like to display an account balance from database using child.getAccountBal(). Before that, i want to use DecimalFormat to display 2 decimal places. I would like to know whether the codes below are correct. Can anybody guide me? Thanks.
    public static double roundTo2DecimalPlaces(double value){
              DecimalFormat df = new DecimalFormat("0.##");
              double d = df.format(value);
              System.out.println(d);
              return value;          
    And inside the jsp page...is that how i call the values?
    Account Balance: <%=roundTo2DecimalPlaces(child.getAccountBal())%>

    DecimalFormat's format method returns a String not a double,
    os you must return a String instead of a double.
    public String roundTo2DecimalPlaces(double value)
         DecimalFormat df = new DecimalFormat("0.00");
         String stringValue = df.format(value);
         return stringValue;
    <%= roundTo2DecimalPlaces(child.getAccountBal()) %>

  • Key figure, number of decimal places are not showing in report output

    Dear experts,
    At cube level PO qty value is getting 0.010 where as in bex report output of PO qty showing as 0. I have chosen decimal places as 0.000 in key figure additional properties tab. In query designer also I have chosen no of decimal places as 0.000 in display propertiesu2026please help me out. How can I get 0.010 value in report o/p.
    Thanks in advance.
    Srivalli.

    Hi,
    Try to run the query in RSRT. CHeck if you are getting the same output. Also make sure that in the reports all the filters are same as you have applied in the info -cube to see the data.
    - Jaimin

  • How can i configure number of decimal places in smartview for Word?

    When I open a smart slice in word via smart view all my values are in scientific notation, I have set the options in excel but they don't come over to word.  Isa there any way to correct this?

    Have you tried formatting the fields in Word?  For example, after bringing in your SmartSlice data, right-click on the field where your data resides and select "Toggle Field Codes" from the Windows menu. Modify the field to look something like this for comma delimited with two decimal places: {=HsGetValue("", "Period#Sep", "Account#Cash")|SmartView14103814190|$#,##0.00|||} Comma delimited with no decimal places: {= HsGetValue("", "Period#Sep", "Account#Cash")|SmartView14103814190|$#,##0|||}

  • Setting number of decimal points using double

    Is it possible to set the number of decimal points
    e.g.
    double a = 2 * Math.random() - 1;
    If I print this it would show something like 0.2342345434332.
    What I want to do is show 0.234.
    Is this possible?

    here you go, you can run this small program to test the results for yourself...
    import java.text.DecimalFormat;
    public class floatTest{
         public static void main( String args[]){
    DecimalFormat threeDig =  new DecimalFormat("0.000");
          double a = 2 * Math.random() - 1;
          //If I print this it would show something like 0.2342345434332.
          System.out.println("double a >" + a);
    System.out.println("formatted>0.000 >" + threeDig.format(a)     );
         }//end of float
    }//end of floatTEstok?

Maybe you are looking for

  • Can you help a novice format an external hard drive?

    Greetings. I'm not very tech literate, so I hope you can help walk me through the following. I have an external 250 GB firewire drive for back up, and I'd like to format and partition it as a bootable drive and also to back up my 2 internal 40 and 20

  • Mountain Lion is not compatible with this computer

    When will I be able to upgrade my Mac Pro to Mountain Lion:  2 x 3 GHz Quad-Core Intel Xeon,  Memory 13gb 667 MHz DR2 FB-DIMM, 64GB free disk (system), 1TB free other disks, computer age mid 2007, Mac OS X Lion 10.7.5. As of 11/28/12:  Mountain Lion

  • HT6181 safari 7.0.3 not opening

    I have safari 7.0.3 and it will not open. Here is the problem report. Process:         Safari [654] Path:            /Applications/Safari.app/Contents/MacOS/Safari Identifier:      com.apple.Safari Version:         7.0.3 (9537.75.14) Build Info:     

  • Frustrated with Droid X

    I am very frustrated with my Droid X....it has been acting up (rebooting, has a delay, keeps going back to the home screen while I'm doing something else on the phone). It started in March....It wouldn't hold a charge while on vacation. Stopped in to

  • Need to generate barcodes

    Hi I need to generate barcodes i've been told that it is possible by report builder, can anyone help me with some hints? Thanks Tony G.