Monday, April 06, 2015

Getting the fractional portion of a number in C#

Quick technique for “truncating” the integer portion of a decimal value in C#, leaving only the fractional portion:

    static decimal GetFractionalPortion(decimal d)
        return d % 1; 

Calling that method with the value 12.34 will return 0.34.

This works because the modulo operator (%) returns the remainder after dividing the first operand by the second, and any value divided by 1.0 returns the fractional portion of the value.

Note that if a negative value is used, the return value (the fractional portion) will also be negative.