Friday, August 10, 2018

How to conditionally set the number of decimal places to display for a number, in Crystal Reports

Symptom

  • How to conditionally change the number of decimals?
       
  • In the Crystal Reports, a number field that returns decimal places is inserted into a report.
    When previewing the report, the decimal places in this number field contain unnecessary zeroes.
    How can you suppress the unnecessary zeroes in these fields and still leave up to two decimal places for fields that require them?
         
    For example:
       
    A number field is placed on a Crystal Report and is not formatted the way you want.
      
    The field displays: 
      
       1.25 
       2.50 
       8.00
      
    But you want the numeber to display like:
        
       1.25
       2.5
       8

Environment

  • SAP Crystal Reports 2008
  • SAP Crystal Reports 2011
  • SAP Crystal Reports 2013
  • SAP Crystal Reports 2016

Resolution

  • To conditionally suppress unnecessary zero values to the right of the decimal for numeric field in Crystal Reports:
        
    1. Right-click the number field and select: 'Format Field'
        
    2. In the 'Format Editor' dialog box, under the 'Number' tab,  click the 'Customize' button.
         
    3. In the 'Decimals' drop-down box, select the maximum number of decimal places to be displayed. 
          
      If you are not sure what the maximum number of decimals will be, click the maximum (1.0000000000).   
          
    4. In the 'Rounding' drop-down box, select the same number of decimal places chosen in the 'Decimal' drop-down box.
            
    5. Click the 'X+2' button to the right of the `Decimals` drop-down box and enter the following formula:
        
         WhilePrintingRecords;
         numberVar counter := 0;
         numberVar numericValue := <INSERT YOUR NUMERIC FIELD HERE>;
         While truncate(numericValue) < numericValue do
         (
             numericValue := numericValue * 10;
             counter := counter + 1
         );
         counter;
          
          
    6. Save this formula. Click 'OK' to close the 'Custom Style' dilaog box, and then click 'OK' to close the 'Format Editor' dialog box.
         
      Now, when you preview the report, unnecessary zeroes to the right of the decimal will not appear. 
          
      For examples:
            
      • 12.30 will display as: 12.3 
      • 12.38 will display as: 12.38 
      • 12.00 will display as: 12
source : https://apps.support.sap.com/sap/support/knowledge/public/en/1212821