[Tex/LaTex] Converting numbers to scientific notations

macrosmath-mode

I have some numbers output from Matlab and I want to show them as tables in LaTeX. The numbers are in the form 0.14190949656253118000 or 0.01234e-3 and I want to show them in scientific notation. How can I find/write, a macro that is called like \scn{0.14190949656253118000} or \scn{0.01234e-3} and results in $1.41x10^{-1}$ or $1.23x10^{-5}$. Note that the number of digits after the decimal points should be configable.

Best Answer

Working from Boris' answer:

\documentclass{article}
\usepackage[scientific-notation=true]{siunitx}
\listfiles
\begin{document}

%\num{0.14190949656253118000}
\num{0.1419094965}

\end{document}

enter image description here

However, for your particular number, siunitx versions lower than 2.4n return a "number too big" error unless you round the number off (as you had originally indicated, but I forgot about). That prompted me to write the following MATLAB function that will print the LaTeX code for your numbers to whatever precision you want:

function s=pp(x,n)
% pretty-print a value in scientific notation
% usage: s=pp(x,n)
% where: x a floating-point value
%        n is the number of decimal places desired
%        s is the string representation of x with n decimal places, and
%          exponent k
exponent=floor(log10(abs(x))); %to accomodate for negative values
mantissa=x/(10^exponent);
s=sprintf('$%*.*f \\times 10^{%d}$',n+3,n,mantissa,exponent);
% returns something like '$1.42 \times 10^{-1}$'

Examples:

>> s1=pp(0.14190949656253118000,2)
s1 =
$1.42 \times 10^{-1}$
>> s2=pp(0.01234e-3,3)
s2 =
$1.234 \times 10^{-5}$

But again, any recent version of siunitx and Boris' answer will work fine for rounded numbers, and siunitx 2.4n will work fine even without rounding.