Tatham Oddie

Tip: Decimals in C#

with 6 comments

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:

Written by Tatham Oddie

April 18, 2006 at 11:19

Posted in Uncategorized

6 Responses

Subscribe to comments with RSS.

  1. And I certainly hope they are using decimal for a reason!! Say huge financial calculations to stop rounding problems or are they just sucking up the extra memory and taking a small performance hit for nothing.

    http://wesnerm.blogs.com/net_undocumented/2004/03/decimal_perform.html

    Justin King

    April 18, 2006 at 12:48

  2. 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.

    RockyH

    April 18, 2006 at 22:30

  3. @ 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!

    Tatham Oddie

    April 20, 2006 at 02:26

  4. 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

    SonnyMal

    April 21, 2006 at 15:59

  5. @SonnyMal – Very astute. Thanks!

    Tatham Oddie

    April 21, 2006 at 16:16

  6. Please send me the code for decimal validation

    Shiv

    August 19, 2006 at 15:51


Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.