Raz Mahato
Raz Mahato

Reputation: 915

Incosistent conversion from object to string

I have a decimal? property called Balance in a class. I have two objects of this class and value for Balance in both object is same (let's say 100). I use reflection to get value of Balance from both objects like this

object bal1= type.GetProperty("Balance").GetValue(object1);
object bal2= type.GetProperty("Balance").GetValue(object2);

When I convert the object to string then I get different values.

Console.WriteLine(bal1.ToString()); // output : 100.00
Console.WriteLine(bal2.ToString()); // output : 100

Can someone explain what is the reason behind this?

Upvotes: 1

Views: 41

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

Balance in both object is same

No, it isn't. A decimal remembers how many significant digits it got assigned. This code:

decimal d1 = 100m;
decimal d2 = 100.000m;

Console.WriteLine(d1);
Console.WriteLine(d2);

Will print:

100
100.000

See also Why does a C# System.Decimal remember trailing zeros?.

Upvotes: 1

Related Questions