How xs:totalDigits Restricts XML Numeric Precision
The xs:totalDigits facet in XML Schema Definition (XSD)
restricts the absolute precision of a numeric data type by defining the
maximum number of decimal digits permitted. This article explains how
xs:totalDigits operates, which data types it applies to,
how it handles both integer and fractional components, and how it pairs
with other facets like xs:fractionDigits to enforce strict
data validation rules.
How xs:totalDigits Works
The xs:totalDigits facet places an upper limit on the
total count of digits in a numeric value. This count includes all digits
present in both the integer part (before the decimal point) and the
fractional part (after the decimal point).
- Applicable Types: It applies to
xs:decimaland all built-in types derived from it, includingxs:integer,xs:long,xs:int,xs:short,xs:byte, and non-negative/positive variants. It does not apply toxs:floatorxs:double, which follow IEEE floating-point representations. - Facet Value Requirement: The value assigned to
xs:totalDigitsmust be a positive integer (xs:positiveInteger), meaning it must be greater than zero. - Zero Handling: Leading zeros before the whole number and trailing zeros after a decimal point (which do not alter the mathematical value) are generally normalized during validation, but any significant digit contributes toward the limit.
Example Usage in XSD
The following schema defines a custom type for a price element that allows a maximum of 5 total digits:
<xs:simpleType name="PriceType">
<xs:restriction base="xs:decimal">
<xs:totalDigits value="5"/>
</xs:restriction>
</xs:simpleType>Valid Values
12345(5 integer digits, 0 fractional digits = 5 total)123.45(3 integer digits, 2 fractional digits = 5 total)1.2(1 integer digit, 1 fractional digit = 2 total)0.1234(0 leading non-zero digits, 4 fractional digits = 4 total)
Invalid Values
123456(6 digits exceeds the limit of 5)1234.56(6 total digits exceeds the limit of 5)0.123456(6 fractional digits exceeds the limit of 5)
Interaction with xs:fractionDigits
xs:totalDigits is frequently combined with
xs:fractionDigits to control exact structural formatting
for financial or measurement data:
<xs:simpleType name="MonetaryAmount">
<xs:restriction base="xs:decimal">
<xs:totalDigits value="7"/>
<xs:fractionDigits value="2"/>
</xs:restriction>
</xs:simpleType>In this configuration: * xs:totalDigits="7" sets the
total precision ceiling to 7 digits. *
xs:fractionDigits="2" restricts the fractional component to
a maximum of 2 digits. * Consequently, the integer portion cannot exceed
5 digits (7 total digits minus 2 fractional digits). * A value like
12345.67 is valid, whereas 123456.7 (6 integer
digits + 1 fraction digit = 7 total) is valid under total digits, but
123456.78 (8 total digits) will fail schema validation.