[Tex/LaTex] Truncation of Napier’s number (e) to an amount of decimal digits of the choice

formattingsiunitxwolfram-mathematica

My students are always very happy when I write a number of decimal digits of the transcendental Napier's number e. I only remember 30 decimal digits as from example. I remind all readers that I'm not an expert of the siunitx package. However, I do know that it is important to correctly process numbers, units and spaces in them. 🙂

enter image description here

\documentclass{article}
\begin{document}
$e=2.718281828459045235360287471352\dots$
\end{document}

Using this widget from wolframalpha of Napier's number I have the possibility to choose the number of decimal places. Is it possible to do the same thing with LaTeX?

Best Answer

I saved 100 decimal digits of e.

\documentclass{article}
\usepackage{siunitx} % also loads expl3 and xparse

\ExplSyntaxOn

\tl_const:Nn \c_sebastiano_napier_tl
 {
  71828182845904523536
  02874713526624977572
  47093699959574966967
  62772407663035354759
  45713821785251664274
 }

\NewDocumentCommand{\napier}{m}
 {
  \num{ 2.\tl_range:Nnn \c_sebastiano_napier_tl { 1 } { #1 } }
 }

\ExplSyntaxOff

\begin{document}

\napier{2}

\napier{18}

\end{document}

enter image description here

With possible line breaks use \napier*.

\documentclass{article}
\usepackage{amsmath}
\usepackage{siunitx} % also loads expl3 and xparse
\showthe\thinmuskip
\ExplSyntaxOn

\tl_const:Nn \c_sebastiano_napier_tl
 {
  71828182845904523536
  02874713526624977572
  47093699959574966967
  62772407663035354759
  45713821785251664274
 }
\cs_generate_variant:Nn \seq_set_split:Nnn { Nnx }

\NewDocumentCommand{\napier}{sm}
 {
  \IfBooleanTF { #1 }
   {
    \sebastiano_napier_inline:n { #2 }
   }
   {
    \num{ 2.\tl_range:Nnn \c_sebastiano_napier_tl { 1 } { #2 } }
   }
 }

\cs_new_protected:Nn \sebastiano_napier_inline:n
 {
  \seq_set_split:Nnx \l_tmpa_seq {} { \tl_range:Nnn \c_sebastiano_napier_tl { 1 } { #1 } }
  2.\seq_indexed_map_function:NN \l_tmpa_seq \__sebastiano_napier_split:nn
 }

\cs_new_protected:Nn \__sebastiano_napier_split:nn
 {
  #2
  \int_compare:nT { \int_mod:nn { #1 } { 3 } = 0 }
   {
    \mode_if_math:TF
     {
      \penalty \c_zero_int
      \mspace{1\thinmuskip plus 1\thinmuskip}
     }
     {
      \hspace{0.16667em plus 0.16667em}
     }
   }
 }

\ExplSyntaxOff

\begin{document}

\napier{2}

\napier{18}

\napier*{99}

$\napier*{99}$

\end{document}

enter image description here

Related Question