Matt
Matt

Reputation: 11327

Require a number of fractional decimal places with an XML schema

I want to restrict the number of fractional decimal places of a number to exactly 2.

For example - 1.00 is valid, but 1, 1.0 and 1.000 are all invalid.

This is a similar question: Specify amount of decimal places of an xs:decimal in an XML schema
and this was the answer provided:

<xs:simpleType name="twoPlacesDecimal" id="twoPlacesDecimal">
    <xs:restriction base="xs:decimal">
        <xs:fractionDigits fixed="true" value="2" />
    </xs:restriction>
</xs:simpleType>

Unfortunately, this only limits the number of decimal places to 2, and allows numbers with zero or one decimal places.

Upvotes: 4

Views: 8062

Answers (3)

Michael Kay
Michael Kay

Reputation: 163322

You can force the number of decimal places to be exactly two using a regex, but is this wise? You're making life harder for anyone who generates documents that are supposed to conform to this schema. For example, they won't be able to use the default serialization produced by XSLT or XQuery, instead they will have to write their own. Isn't it better to change the spec to be a bit more liberal in what it accepts?

Upvotes: 4

mellamokb
mellamokb

Reputation: 56769

I don't think you can do that with the total and fractionDigits restrictions alone, but it may be possible with a Regex pattern restriction, something like:

<xs:restriction base="decimal">
  <xs:pattern value="[+-]?\d+\.\d{2}"/>
</xs:restriction>

Upvotes: 4

Dave
Dave

Reputation: 5173

When I've done this in the past, I used a regex matcher. The regex you can use is something like this:

<xsd:simpleType name="exactlyTwoAfterDecimal">
    <xsd:restriction base="xsd:token">
        <xsd:pattern value="^-?\d+\.\d\d$"/>
    </xsd:restriction>
</xsd:simpleType>

Upvotes: 2

Related Questions