Decimal validation against XSD

46 Views Asked by At

My XSD contains simple type based on decimal with additional restrictions:

  <xs:restriction base="xs:decimal">
    <xs:totalDigits value="10"/>
    <xs:fractionDigits value="3"/>
  </xs:restriction>

I'm using XmlReader with XmlReaderSettings (with ValidationType.Schema and XmlSchemaValidationFlags.ReportValidationWarnings).

The reader behaves well for most decimals with fraction except cases with 0.9(9). Let's start with 0.9.

This is ok:

Xml       : <Test><Value>0.9</Value></Test><!-- number of frag digits: 1 -->
Value     : Test { Value = 0.9 }

It is similar for cases from 0.9 to 0.999.

The validation works as expected for all the cases from 0.9999 to 0.9999999999999999999999999999 - the XML is invalid.

Xml       : <Test><Value>0.9999</Value></Test><!-- number of frag digits: 4 -->
Validation: The 'Value' element is invalid - The value '0.9999' is invalid according to its datatype 'RatingType' - The FractionDigits constraint failed.
Value     : Test { Value = 0.9999 }

...

Xml       : <Test><Value>0.9999999999999999999999999999</Value></Test><!-- number of frag digits: 28 -->
Validation: The 'Value' element is invalid - The value '0.9999999999999999999999999999' is invalid according to its datatype 'RatingType' - The TotalDigits constraint failed.
Value     : Test { Value = 0.9999999999999999999999999999 }

And surprisingly after 28 nines - the XML is again valid.

Xml       : <Test><Value>0.99999999999999999999999999999</Value></Test><!-- number of frag digits: 29 -->
Value     : Test { Value = 1.0000000000000000000000000000 }

...

Xml       : <Test><Value>0.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999</Value></Test><!-- number of frag digits: 99 -->
Value     : Test { Value = 1.0000000000000000000000000000 }

I suppose that it happens because .NET first parses the string to Decimal (rounding), then checks fragDigit restriction (which allows additional zeros at the end).

My question is - what is the best/simplest way to prevent this behavior? What should I do to properly validate 0.9(9)?

0

There are 0 best solutions below