function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
swain 10swain 10 

Rounding a value to nearest 0.5 hour(nearest 0.5 ) for a text field

Text Field(hours) = (a.StartDateTimeField.date().daysBetween(EndDateTimeField.date()) *24));

How to round off the value to nearest 0.5 example if the value is 24.3 then round to 24 if 24.6 then 25 if 24.5 then(24 or 25). How to do that?
Best Answer chosen by swain 10
Alain CabonAlain Cabon
@Swain

The rounding mode is quite complicated.

decimal_number..round(System.RoundingMode.HALF_EVEN)
decimal_number..round(System.RoundingMode.HALF_UP)
decimal_number..round(System.RoundingMode.HALF_DOWN)

decimal_number..round(System.RoundingMode.CEILING)
decimal_number..round(System.RoundingMode.FLOOR)
decimal_number..round(System.RoundingMode.UP)

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_decimal.htm

Here is some code to test the results:
Decimal[] example = new Decimal[]{5.5, 2.5, -5.5, -2.5, 1.1, -1.1, -2.7, 1239.09};
Long[] expected = new Long[]{6, 2, -6, -2, 1, -1, -3,1239};
for(integer x = 0; x < example.size(); x++){
    System.assertEquals(expected[x],
        example[x].round(System.RoundingMode.HALF_EVEN));
    system.debug(example[x] + ' HALF_EVEN =' + example[x].round(System.RoundingMode.HALF_EVEN) + 
                + ' HALF_UP =' + example[x].round(System.RoundingMode.HALF_UP)
               +  ' HALF_DOWN =' + example[x].round(System.RoundingMode.HALF_DOWN) );
}

2.5 : HALF_EVEN = 2 => 2 is the digit to the left of the decimal point, is even => HALF_DOWN rounding method => 2
5.5 : HALF_EVEN = 6 => 5 is the digit to the left of the decimal point, is odd => HALF_UP rounding method => 6

-2.5 : HALF_EVEN = -2 => -2 is the digit to the left of the decimal point ,is even => HALF_DOWN rounding method => -2
-5.5 : HALF_EVEN = -6 => -5 is the digit to the left of the decimal point, is odd  => HALF_UP rounding method => -6

https://developer.salesforce.com/forums/?id=9060G0000005pKSQAY

Other samples in java 7:

https://docs.oracle.com/javase/7/docs/api/java/math/RoundingMode.html