An incredible bug in decimal.ToString()

S

Simon Law

Hi,

This is unbelievable and totally the craziest thing I've ever seen.
Code:
decimal d1=decimal.Parse("2");
decimal d1=decimal.Parse("2.0");
decimal d1=decimal.Parse("2.00");
string s1=d1.ToString();
string s2=d2.ToString();
string s2=d3.ToString();
gives
s1="2"
s2="2.0"
s3="2.00"

This happens under .NET framework 1.1, but not 1.0.

decimal.ToString() should return a string using "G" format.

Simon.
 
R

Robert Jordan

Simon said:
Hi,

This is unbelievable and totally the craziest thing I've ever seen.
Code:
decimal d1=decimal.Parse("2");
decimal d1=decimal.Parse("2.0");
decimal d1=decimal.Parse("2.00");
string s1=d1.ToString();
string s2=d2.ToString();
string s2=d3.ToString();
gives
s1="2"
s2="2.0"
s3="2.00"

This happens under .NET framework 1.1, but not 1.0.

decimal.ToString() should return a string using "G" format.

I cannot find any unbelievable and crazy things inside(TM).
..NET 1.0 ToString("G") doesn't return the fractional part
when it's zero. Never user the general format when you
expect compatibility with non-dotNet code.

bye
Rob
 
J

Jon Skeet [C# MVP]

Simon Law said:
This is unbelievable and totally the craziest thing I've ever seen.
Code:
decimal d1=decimal.Parse("2");
decimal d1=decimal.Parse("2.0");
decimal d1=decimal.Parse("2.00");
string s1=d1.ToString();
string s2=d2.ToString();
string s2=d3.ToString();
gives
s1="2"
s2="2.0"
s3="2.00"

This happens under .NET framework 1.1, but not 1.0.
Yup.

decimal.ToString() should return a string using "G" format.

And indeed it does. From the docs for standard numeric format strings,
the "G" specifier in particular:

<quote>
The exception to the preceding rule is if the number is a Decimal and
the precision specifier is omitted. In that case, fixed-point notation
is always used and trailing zeroes are preserved.
</quote>

This is all by design - the behaviour changed from 1.0 to 1.1 because
MS recognised that for some applications you really need to keep the
number of trailing zeroes.

See http://www.yoda.arachsys.com/csharp/decimal.html for a bit more on
this.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top