Tip: Decimals in C#

I have noticed some people writing code like this to get a decimal in their code:

decimal amount = decimal.Parse("10.00");

It’s not that obvious, but you can write this which is better:

decimal amount = 10.00M;

If you don’t include the M then the compiler thinks you are typing a double which is why it won’t compile.

technorati tags:

6 comments

  1. This is interesting, but you don’t find a lot of call for hard coded strings to be converted to decimal. The issue is that the ‘M’ won’t work if you are dealing with a variable, or even worse, a value from a DataRow column. xxxx.Parse(…) is used for changing variables and unknown strings to their appropriate numeric types. ‘M’ can’t be used with variables, which is where Parse is normally used, because you’d end up changing the variable name.

    You wouldn’t ever use Parse for a known fixed string. I can’t imagine anyone writing decimal amount = decimal.Parse(“10.00”); when they would just write decimal amount = 10.00;

    If they are doing as you suggest above, then they have much more serious problems than not knowing about the M.

  2. @ Justin – it is financial related code … however doesn’t involve huge calculations so I’ve asked them to swap it all back to a double. Thanks for the link.

    @ Rocky – the code snip I posted was a direct copy-paste from the actual codebase … there wasn’t a parameter being passed in or anything. Hence why I was scared!

  3. Hmmm, Your example is wrong. The ‘M’ is at the start of the decimal value instead of the end.

    decimal amount = M10.00;

    Should be

    decimal amount = 10.00M;

    Cheers

Comments are closed.