Search code examples
c#currencymodulus

How to calculate remainder while accounting for hundredths digit for currency operations


I need to divide a USD amount by a number of months for a payment schedule, and I want to be able to get the remainder of the division if the money doesn't divide cleanly. Normally I would just use a modulus operation to get the remainder but I need to also account for the hundredths place, which modulus doesn't do. $500.00 divvied up over 8 months is a perfectly valid amount at $62.50 but a mod operation will return $4.00.

I'm currently using the decimal type for my currency operations, is there a better way to do what I'm doing or should I just go about and write a function that does this?


Solution

  • You can calculate the remainder in cents by multiplying up, then applying mod and then dividing back down:

    ((value * 100) % 8 ) / 100