TeX - LaTeX Asked on July 11, 2021
I have created a macro that draws a triangle with a given height. I would like the three base lengths to be formatted as 5, 5.4 and 6 respectively. What is the best way to achieve this? Wold it be within tikz
or siunitx
? I did try something from tikz
but then my file didn’t compile.
documentclass[12pt]{article}
usepackage{tikz}
usepackage{siunitx}
newcommand{triangleSHS}[4][]{%
begin{tikzpicture}[x=1cm,y=1cm,#1]
coordinate (O) at (0,0);
path (O) ++(0:#2) coordinate (X);
path (X) ++(90:#3) coordinate (B);
path (X) ++(0:#4) coordinate (A);
pgfmathparse{add(#2,#4)}
draw (O)--node[below]{SI{pgfmathresult}{centimetre}}(A)--(B)--(O);
draw[dashed] (X)--node[right]{SI{#3}{centimetre}}(B);
end{tikzpicture}
}%
begin{document}
triangleSHS{2}{4}{3}
triangleSHS{2.1}{4.2}{3.3}
triangleSHS{2.5}{4}{3.5}
end{document}
Using the rounding capabilities of siunitx:
You just have to pass a few options:
round-mode=places
. Will set the rounding precision to the number of decimal places.round-precision=1
. This, with the previous options, will give you one decimal place.zero-decimal-to-integer
. This one will round the 5.0
to 5
to give what you want.You can pass the options locally to SI
with:
SI[round-mode=places, round-precision=1,zero-decimal-to-integer]{pgfmathresult}{centimetre}
or globally with:
sisetup{round-mode=places, round-precision=1,zero-decimal-to-integer}
and then:
SI{pgfmathresult}{centimetre}
Code with the options set locally:
documentclass[12pt]{article}
usepackage{tikz}
usepackage{siunitx}
% Global configuration:
% sisetup{round-mode=places, round-precision=1,zero-decimal-to-integer}
newcommand{triangleSHS}[4][]{%
begin{tikzpicture}[x=1cm,y=1cm,#1]
coordinate (O) at (0,0);
path (O) ++(0:#2) coordinate (X);
path (X) ++(90:#3) coordinate (B);
path (X) ++(0:#4) coordinate (A);
pgfmathparse{add(#2,#4)}
draw (O)--node[below]{SI[round-mode=places, round-precision=1,zero-decimal-to-integer]{pgfmathresult}{centimetre}}(A)--(B)--(O);
draw[dashed] (X)--node[right]{SI{#3}{centimetre}}(B);
end{tikzpicture}
}%
begin{document}
triangleSHS{2}{4}{3}
triangleSHS{2.1}{4.2}{3.3}
triangleSHS{2.5}{4}{3.5}
end{document}
Correct answer by Phelype Oleinik on July 11, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP