C# Tips

C# Tip Article

Integer division to get decimal result

Question

Sometimes Web API can return money data as an integer.

For example, Stripe API (from stripe.com) returns 3025 for $30.25.
So how can we convert from integer 3025 to 30.25?

Tip

We can think of many different ways.

For example, when int i = 3025,
 
A) decimal a = i / 100;
B) decimal b = (decimal)( i / 100 );
C) decimal c = (decimal)( i / 100.0);
 
In case of A, the result is 30 since operand i and 100 are both integers and so it truncates .25.
Case B looks like a valid one but it first calculates i / 100 whose result is 30 and then convert 30 to decimal. So the result becomes 30 in decimal type. 
Case C is little more interesting. In case of C, i is divided by 100.0. Since the type of 100.0 is double, the expression results in double type including .25 data. Once it gets double 30.25, then it converts to decimal type. 
This can give us correct answer, but better way is to convert i to decimal first : (decimal) i / 100.

Answer

First cast i to decimal type and divide by 100.

‚Äč
int i = 3025;
decimal a = (decimal) i / 100;