Fancy a small byte? Difference between double and decimal numbers (small byte 1)

Why ‘small byte’?

In my work or when I’m learning in my free time, I often discover useful commands, methods or shortcuts. I use these repeatedly, but sometimes I need to look them up again. From my teaching days I recall one of my tutors saying that you don’t truly remember a word or phrase in a language until you have used it on average six times. Therefore I have decided to start a series of short posts with bits that I have found useful, so that I have a record of them, use them again and help others. When I was taking my son to the childminder this morning I had a brainwave about the category name for these posts – ‘small bytes’. So, here we go, small byte 1.

This week at work I had to do a task, one part of which included calculating a rounded percentage or two integers. For example if the result was 38.2, rounding up would make it 38 and if the result was 38.5, rounding up would take it to 39.

Things I have learnt during this task:

  • the result of the same operation when casting numbers to either decimal or double is not the same:
  • you need to cast divisor and dividend as double because decimal is used mostly for financial calculations because of extra precision
  • double is a 64-bit floating point number, and decimal is a 128-bit floating point number
  • decimal operations take longer to execute because of precision

And finally, to round the result you can use Math.Round:

Math.Round((double)(100 * itemsSold) / (double)itemsInStock)