Home > .Net, Programming > Careful with That Axe, Eugene – Using ToString() with a .Net Decimal Type

Careful with That Axe, Eugene – Using ToString() with a .Net Decimal Type

A Problem With Decimals

Yesterday I ran into a problem with the ToString() function on a .Net Decimal type.

Actually the problem was mine but it revealed something I didn’t know about Decimal types that actually IS in the documentation but no one really reads the documentation, do they? Well they do when they run into problems.

Try the following in a .Net console application (C# or VB.Net or whatever you prefer):

    decimal dec1 = 10.0M;
    decimal dec2 = Decimal.Parse("10.00");
    Console.Write("dec1 == dec2 : ");
    Console.WriteLine(dec1 == dec2);
    Console.Write("dec1.ToString() == dec2.ToString() : ");
    Console.WriteLine(dec1.ToString() == dec2.ToString());

The output is the following:

dec1 == dec2 : True

dec1.ToString() == dec2.ToString() : False

Now, both dec1 and dec2 contain a decimal 10 value so mathematically they are equal, but the output of ToString() for each of them is:

dec1.ToString() : 10.0

dec2.ToString() : 10.00

So you see the strings are not identical.

The Reason Behind It

The reason that the two ToString() calls are not equal is because Decimal preserves the position of the decimal point so when we parse the string “10.00” both zeros to the right of the decimal point are kept.

This is all detailed in the MSDN documentation on the Decimal structure :

The scaling factor also preserves any trailing zeroes in a Decimal number. Trailing zeroes do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeroes can be revealed by the ToString method if an appropriate format string is applied.

I stumbled upon this while working on the Serialize/De-serialize functions of PropertyTree a data structure that I will post about soon (really).

Technorati Tags: ,
Advertisements
Categories: .Net, Programming Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: