Technical Article

Locale-Neutral PDF Numbers for Comma-Decimal Delphi Apps

Switch a Windows test box to German regional settings, run a routine that prepends a scale-and-shift matrix to a page, and dump the content stream. Instead of 0.5 0 0 0.25 0.00001 12.75 cm you get 0,5 0 0 0,25 1E-5 12,75 cm. A content parser reads that as the number 0, then a token ,5 it does not recognize, then more numbers that no longer line up with the six operands cm expects, and the page draws with a transform you never asked for. Numbers that a machine will parse need a fixed dot, no exponent and no dependency on FormatSettings at all, on the writing side and on the reading side

Why does a comma-decimal locale break PDF numbers?

A comma-decimal locale breaks PDF numbers because Delphi's default float formatting follows the desktop, while PDF number syntax is fixed. FloatToStr uses FormatSettings.DecimalSeparator, so on a de-DE, fr-FR or pt-BR machine every fraction comes out with a comma. ISO 32000-1 §7.3.3 allows digits, one period and a leading sign in a number. Nothing else. The comma therefore splits one number into a valid integer plus junk, and the result is a page that renders, just wrongly

There is a second trap behind the first, and it bites on US machines too. FloatToStr uses the ffGeneral format, which switches to exponent notation once the magnitude drops below 1E-4, so a tiny offset is written as 1E-5. The same §7.3.3 says PDF does not support the exponent form. Tracing either problem back from the rendered output is miserable, because a drifted matrix looks exactly like a layout bug in your own code and nothing on the page points at the regional settings

PDFlibPas, the losLab PDF Developer Library for Delphi, writes the operands of AddPageMatrix through PLDoubleToStrConst with six decimal places, and the call sites that generate page content on your behalf follow the same rule. The cheapest regression test we know of flips the separator to a comma inside the process, calls the API and scans the result for commas and exponents:

uses
  System.SysUtils, PDFlibrary;

// Your own check, not part of the library. It is crude on purpose:
// text strings such as (Hello, world) Tj also contain commas, so run it
// on a test page that only draws shapes
function HasLocaleDamage(const Content: AnsiString): Boolean;
var
  I: Integer;
begin
  Result := False;
  for I := 1 to Length(Content) do
  begin
    if Content[I] = ',' then
      Exit(True);
    if (Content[I] in ['E', 'e']) and (I > 1) and (I < Length(Content)) and
       (Content[I - 1] in ['0'..'9']) and (Content[I + 1] in ['0'..'9', '-', '+']) then
      Exit(True);
  end;
end;

var
  Lib: TPDFlib;
  OldSeparator: Char;
  Content: AnsiString;
begin
  Lib := TPDFlib.Create;
  try
    Lib.SetPageDimensions(300, 200);
    Lib.DrawBox(10, 10, 20, 20, 1);
    OldSeparator := FormatSettings.DecimalSeparator;
    try
      FormatSettings.DecimalSeparator := ',';   // behave like a de-DE desktop
      Lib.AddPageMatrix(0.5, 0.25, 1E-5, 12.75);
      Content := Lib.GetPageContentToString;
      // Expected: 0.5 0 0 0.25 0.00001 12.75 cm
      // FloatToStr would have produced: 0,5 0 0 0,25 1E-5 12,75 cm
      Writeln(Content);
      if HasLocaleDamage(Content) then
        Writeln('Locale leaked into the content stream');
    finally
      FormatSettings.DecimalSeparator := OldSeparator;
    end;
  finally
    Lib.Free;
  end;
end;
Locale-bound number formatting on a comma-decimal desktop writes 0,5 0 0 0,25 1E-5 12,75 cm, which a PDF parser reads as the number 0 plus unknown tokens, leaving cm with wrong operands and the page silently transformed, while PLDoubleToStrConst writes valid dot decimals
The comma is not a number character in PDF syntax, so the damage reads as valid tokens with the wrong meaning — and ffGeneral exponents like 1E-5 are invalid on every locale, not just comma ones

Changing FormatSettings.DecimalSeparator in-process is a shortcut. It does not exercise code that builds its own TFormatSettings from the OS, so if your application does that, a CI agent with real German regional settings is the more honest test

Two kinds of numbers, two families of helpers

PDFlibPas splits its number helpers by audience: text shown to people may follow the locale, and anything written for a machine never does. PLFloatToStr and PLStrToFloat in PDFlibExtra.pas are thin wrappers over FloatToStr and StrToFloat, and the comment on their declaration says they are for human-readable text only. Machine output (PDF, FDF, XFDF, JSON, XML, CSV) goes through the invariant family instead: PLDoubleToStrConst for writing, PLTryStrToFloatInvariant for reading, and PLInvariantFormatSettings when you need a TFormatSettings record with a dot decimal for your own TryStrToFloat calls

Precision is chosen per job rather than globally. Matrices get six decimals, coordinates and TJ adjustments get four, colors and FDF rectangles get three. The machine-facing side covers more places than the API surface suggests:

  • AddPageMatrix, ScalePage and DeskewPage, which all prepend a cm to existing page content
  • The Tm resets, TJ advances and cm transforms written when page elements are generated
  • Glyph placement matrices and outline points produced when text is converted to paths
  • The black fill box that RedactRegion prepends, the /Rect values in FDF export and the color operands that recoloring writes

PLDoubleToStrConst is a hand-rolled formatter, and we think that was the right call over wrapping FloatToStrF with a fixed TFormatSettings. ffFixed still falls back to scientific notation once the integer part outgrows the precision, and it would leave 0.500000 where 0.5 is shorter and identical. The custom routine always writes a period, strips trailing zeros and never writes an exponent for finite input. It also keeps the significant digits of a non-zero value that is smaller than the requested precision: PLDoubleToStrConst(1E-9, 6) returns 0.000000001, and only values below about 5E-16 become 0. Rounding a tiny scale factor to zero would turn a valid matrix into a singular one, which is a worse failure than any misplaced decimal

PDFlibPas splits number formatting in two: PLFloatToStr and PLStrToFloat stay locale-bound for user-facing text, while PLDoubleToStrConst and PLTryStrToFloatInvariant format everything that becomes PDF syntax with a dot, no exponent and a fixed per-job precision of six, four or three decimals
The invariant formatter is hand-rolled on purpose: it strips trailing zeros, never writes an exponent, and keeps the significant digits of tiny values, because rounding a scale factor to zero would turn a valid matrix singular

If you write unit tests against the formatter, pick your sample values with binary floating point in mind. The obvious choice for "four significant digits" is 0.000012345, but multiplied by 1E8 that double is 1234.4999…, so the result is 0.00001234 and the assertion fails for a reason unrelated to locales. A value that sits clearly off the midpoint, such as 0.000012346, avoids the argument entirely:

uses
  PDFlibExtra;

// Assert calls are checks you add in your own test project
procedure CheckNumberHelpers;
var
  V: Double;
begin
  // Machine output: dot decimal, no exponent, trailing zeros stripped
  Assert(PLDoubleToStrConst(1E-5, 6) = '0.00001');
  Assert(PLDoubleToStrConst(-0.5, 6) = '-0.5');
  Assert(PLDoubleToStrConst(0.000012346, 4) = '0.00001235');  // 4 significant digits kept
  Assert(PLDoubleToStrConst(12345.25, 4) = '12345.25');

  // Machine input: False instead of EConvertError
  Assert(PLTryStrToFloatInvariant('0.5', V) and (V = 0.5));
  Assert(PLTryStrToFloatInvariant('  12.75 ', V) and (V = 12.75)); // input is trimmed
  Assert(not PLTryStrToFloatInvariant('0,5', V));   // content numbers never use a comma
end;

Why is the parsing side more dangerous than the writing side?

The parsing side is more dangerous because a locale-bound parser does not produce a slightly wrong number; it raises. StrToFloat throws EConvertError whenever the text does not match the system separator. A recoloring pass built on it would abort the moment it reached an ordinary 0.5 g operator on a comma-decimal machine, which means it fails on practically every real page. A clip string such as "10.5,20.5,50.5,40.5" would be rejected outright, and SVG lengths, SVG colors, annotation vertex lists and output intent values would either be refused or quietly replaced by defaults. That is code that passes every test on the developer machine and fails for the first customer in Munich, the same family of problem as the cases in the article on Delphi code that works by accident

Every StrToFloat-style call in the library is sorted by where its input comes from. Content stream operands, SVG attributes, painter color strings and comma-separated clip and vertex lists all have a fixed dot syntax, so they go through PLTryStrToFloatInvariant. That helper trims the text, parses it with PLInvariantFormatSettings and returns False (with the value set to 0) for empty, malformed, NaN or infinite input. Comma-separated lists needed no debate at all: a comma cannot be both the list delimiter and the decimal mark, so there is no legacy form to stay compatible with

For the recoloring pipeline described in the guide to converting a PDF to one color space, the result is that RecolorPage and RecolorDocument parse page content identically on every locale. Rule values that a caller types into CheckDocumentPolicy are the one parsing case that takes the lenient route, because a person typed that string and may well have used the local decimal mark

A number relayed through a string needs both ends to agree

When a number is written to a string by one part of the code and parsed back by another, the writer and the reader have to follow the same convention, and changing only one of them breaks the round trip. Tagged PDF structure attributes work exactly this way. SetStructElemBBox formats four values into one string and stores it through AddTagAttribute. When the /A attribute dictionary is written, that string is parsed again to decide whether it becomes a number, an array or a name

If both ends followed the system locale, the trip would be self-consistent on a German machine. The trouble starts with a caller who follows the documentation and passes "0.5" to AddTagAttribute: a locale-bound reader cannot parse it and emits the PDF name /0.5. PDF/VCR placeholders hit the mirror image, since their GTS_BBox is generated with a dot and a locale-bound validation step before saving would reject it. And switching only the writer to a dot makes things worse, because every SetStructElem* value would then turn into a name on comma-decimal systems

So the writers use PLDoubleToStrConst(v, 6) and the reader uses PLTryStrToFloatLenient, which tries the dot form first and falls back to the system locale. A comma-locale caller who passes "1,25" gets the number 1.25. There is a cost, and we accepted it knowingly: on a German system "1.500" is read as 1.5 rather than one thousand five hundred, because the dot form wins. The API documents the dot as the separator, so a German-style thousands group in an attribute string is the input we chose to give up on. Literal NAN and INF strings are not treated as numbers

PDFlibPas SetStructElemBBox and its siblings relay numbers as strings through AddTagAttribute, and the /A writer parses those strings back, so both ends move together: PLDoubleToStrConst writes with a dot and PLTryStrToFloatLenient reads dot first with a locale fallback so a comma-locale 1,25 still reads as 1.25
Fixing only the writer would degrade every structured element attribute into a PDF name, which is why a round trip moves both ends together or not at all
uses
  System.SysUtils, PDFlibrary;

var
  Lib: TPDFlib;
begin
  FormatSettings.DecimalSeparator := ',';   // comma-decimal caller
  Lib := TPDFlib.Create;
  try
    Lib.BeginTag('Figure', 'Sales chart', '');
    Lib.SetStructElemBBox(10.5, 20.25, 200.5, 100.75); // /BBox [ 10.5 20.25 200.5 100.75 ]
    Lib.AddTagAttribute('Layout', 'SpaceAfter', '0.5');   // /SpaceAfter 0.5 rather than /0.5
    Lib.AddTagAttribute('Layout', 'StartIndent', '1,25'); // /StartIndent 1.25 via the locale fallback
    Lib.DrawText(20, 20, 'figure');
    Lib.EndTag;
    Lib.SaveToFile('tagged.pdf');
  finally
    Lib.Free;
  end;
end;

Our recommendation for your own code is to pass dot-decimal strings to AddTagAttribute and leave the comma fallback for values you cannot control, such as strings loaded from an older configuration file. How the structure tree around those attributes is built is covered in the tagged PDF structure guide

Where NaN and infinity get stopped

AddPageMatrix, ScalePage and RedactRegion reject NaN and infinite arguments up front and return 0, since no PDF number can represent either. The check has to be explicit. NaN slips past a <= 0 test, so a range check on a scale factor alone would let a NaN scale travel all the way to the formatter, and calling Round on NaN raises EInvalidOp on Win32, where the x87 unit does not mask invalid operations by default. PLDoubleToStrConst writes 0 for NaN as a last line of defense, but a zero inside a matrix is a singular transform, so the API-level check is the one that actually protects the page. In your own code, test the return value: when ScalePage returns 0 for a factor you computed, print the factor before anything else, because a 0/0 somewhere upstream produces exactly this NaN

Two boundaries are deliberate. Metafile state strings are written and read with the locale inside a single process and never reach a file, so they stay locale-bound. And if you test small values through the page generation path, read the content right after the call: an operation that later re-emits the page content at the document's coordinate precision will legitimately turn 1E-5 into 0, and that is rounding, not a locale leak

The habit worth adopting is short. Run the PDF-producing paths of your application once with a comma separator, scan the output for commas and exponents, and keep FloatToStr out of anything a parser will read. Numbers read from an existing file follow a related rule, covered in the article on preserving parsed decimal precision, where the exact source text survives a save. Trial builds, the API reference and licensing details are on the PDFlibPas Delphi PDF library product page