Why the decimals 1.00M and 1.000000M differ in C#
I had a strange problem. I tried to assign a decimal variable to an SAP web service. But I got error CX_SY_CONVERSION_LOST_DECIMALS for decimal place exceeding above the limit.
I solved it by using Math.Round(Decimal, Int32) Method
Here is my doubt.
i = 1.23450M; j = Math.Round(i, 2); // 1.23M
(i != j) == true, since the value has difference
i = 1.000000M; j = Math.Round(i, 2); // 1.00M
I can assign j to the field in web service, but not i. Now what is the difference between i and j? Why does it happen?
For reference from WSDL, ignore if out of topic.
<xsd:element name="MyVar" type="tns:curr15.2" /> <xsd:simpleType name="curr15.2"> <xsd:restriction base="xsd:decimal"> <xsd:totalDigits value="15" /> <xsd:fractionDigits value="2" /> </xsd:restriction> </xsd:simpleType>
Now what is the difference between i and j?
i has 6 decimal places of precision; j only has 2. Sure, the difference doesn't change the magnitude of the number at all - and i == j will still return true - but decimal retains the number of decimal places, and presumably your web service client code notices that you're specifying more than will be preserved.
From the documentation:
The scaling factor also preserves any trailing zeros in a Decimal number. Trailing zeros do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeros might be revealed by the ToString method if an appropriate format string is applied.
This is one of the significant differences between decimal and float/double in .NET.