Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to multiply a decimal with an int?

Tags:

I'm a newbie to C# and .NET, so I apoligize if this is a too simple question.

I have a decimal variable decVar. I need to multiply it with an integer variable intVar. I need the result to be decimal. So should I then declare the integer variable as int or as decimal?

Having this code,

decimal decVar = 0.1m; decimal decRes = decVar * intVar; 

should I declare it like this:

int intVar = 3; 

or like this:

decimal intVar = 3; 

?

This is a financial calculation, so I need the result to be exactly 0.3.

upd : Code updated (thanks to Jon)

like image 907
Oleg Vazhnev Avatar asked Oct 27 '11 19:10

Oleg Vazhnev


1 Answers

It doesn't matter - the int will be converted to decimal anyway: there isn't a *(decimal, int) operator, just *(int, int) and *(decimal, decimal). (And other types, of course.)

Now decimal can't be implicitly converted to int, but the reverse conversion is valid - so that's what the compiler does.

However, you'll need to change the declaration of decVar as currently the right hand side of the assignment operator is a double, not a decimal. You mean 0.1m. You'll want semi-colons too :)

like image 65
Jon Skeet Avatar answered Oct 03 '22 02:10

Jon Skeet