The reason is basically the same as Enforcing Order of Operations on Dimension Expressions?
just on an internal level of TikZ.
The value, for example 4cm-1cm, simply gets stored in the key /pgf/decoration/post length. Somewhere in the decoration code it is retrieved via \pgfkeysvalueof{/pgf/decoration/post length} and this is just a “dumb” replacement.
Somewhere in the code of the decoration the expression
\pgfmetadecoratedremainingdistance-\pgfkeysvalueof{/pgf/decoration/post length}
will be calculated which is
<some value>-4cm-1cm
which mathematically is the same as
<some value>-5cm
and not
<some value>-(4cm-1cm)
I'd argue that is somewhat of a bug in TikZ.
Similar things happen with the delta angle whose value is just subtracted from the end angle (when no start angle is given, of course). (See for example another answer of mine where I'm using () around the ternary operator because that was doing very weird things.)
So you will need parentheses (the {} braces get stripped by PGFKeys)
\draw[blue,
decoration={moveto, post=lineto, post length=(4cm+1cm)}, decorate
] (0,-2) --node{4cm+1cm} (5,-2);
\draw[orange,
decoration={moveto, post=lineto, post length=(4cm-1cm)}, decorate
] (0,-3) --node{4cm-1cm} (5,-3);
or evaluate the result before the decoration code gets to it:
\draw[blue,
decoration={moveto, post=lineto, post length/.evaluated=4cm+1cm}, decorate
] (0,-2) --node{4cm+1cm} (5,-2);
\draw[orange,
decoration={moveto, post=lineto, post length/.evaluated=4cm-1cm}, decorate
] (0,-3) --node{4cm-1cm} (5,-3);
Technically, this will store a result without units in the key but this will get converted to pt again by PGFMath.
Of course, you can just do
\pgfmathset(length)macro\<something>{4cm±1cm}
and then use \<something> instead.
(A \dimexpr gets handed off to eTeX when PGFMath gets to it and since that is greedy it grabs as much as it can get.)
post length=(4cm±1cm)work? – Qrrbrbirlbel Dec 20 '22 at 15:22siunitx– hpekristiansen Dec 20 '22 at 16:53