![截断浮点数以便显示,同时保持计算的完整准确性](https://linux22.com/image/352670/%E6%88%AA%E6%96%AD%E6%B5%AE%E7%82%B9%E6%95%B0%E4%BB%A5%E4%BE%BF%E6%98%BE%E7%A4%BA%EF%BC%8C%E5%90%8C%E6%97%B6%E4%BF%9D%E6%8C%81%E8%AE%A1%E7%AE%97%E7%9A%84%E5%AE%8C%E6%95%B4%E5%87%86%E7%A1%AE%E6%80%A7.png)
下面的 MWE 表明截断fp
类型数字不仅仅是为了美观,实际上还会改变数字的值。有没有办法减少显示的小数位数,而不会影响数字在计算中的完整准确性?我浏览了一下,siunitx
但什么也没发现。
\documentclass{article}
% RN. 6 April 2017
% TOPIC:
% Truncating floating point numbers
%=======================
\usepackage[check-declarations]{expl3}
\usepackage{xparse}
%-----------------------
\ExplSyntaxOn
\NewDocumentCommand\myTruncatingFloatingPoints{mO{3.11998}O{3.0198}}
{
\fp_eval:n {trunc(#2,#1)*trunc(#3,#1)}
} % \myTruncatingFloatingPoints
\ExplSyntaxOff
%-----------------------
\begin{document}
1. Full complement of digits:~\myTruncatingFloatingPoints{5}
2. Truncated to 2 decimal digits:~ \myTruncatingFloatingPoints{2}
\end{document}
答案1
取自如何设置数字的精度(还有更多版本,请查看):
\documentclass{article}
\usepackage{siunitx}
\begin{document}
\num{0.12368455}
\num[round-mode=places,round-precision=4]{0.12368455}
\end{document}
这就是你要找的东西吗?
答案2
这里我\num
仅使用漂亮的打印。
\documentclass{article}
\usepackage{siunitx,xfp}
\begin{document}
\begin{tabular}{ll}
No truncation & \num{\fpeval{3.11998*3.0198}} \\
Truncation & \num{\fpeval{trunc(3.11998*3.0198,2)}} \\
Bad truncation & \num{\fpeval{trunc(3.11998,2)*trunc(3.0198,2)}}
\end{tabular}
\end{document}
答案3
因为我感觉像是在重新发明轮子……(再次)
已编辑,因此截断到 0 位不会显示小数。
重新编辑以处理负数。
\documentclass{article}
\newcounter{digits}
\newcommand\myTruncatingFloatingPoints[2]{%
\whole{#1}#2..\relax%
}
\def\whole#1#2.#3.#4\relax{%
\presentwhole#2\relax\relax%
\ifx\relax#3\relax.\trunc{#1}00\relax\else%
\ifnum#1>0\relax.\trunc{#1}#3\relax\fi%
\fi%
}
\def\presentwhole#1#2\relax{%
\ifx-#1\ensuremath{-}\the\numexpr0#2\else\the\numexpr0#1#2\fi%
}
\def\trunc#1#2#3#4\relax{%
\setcounter{digits}{#1}%
\addtocounter{digits}{-1}%
\ifnum\thedigits>0\relax%
#2%
\trunc{\thedigits}#3#40\relax%
\else%
\ifnum#3<5\relax#2\else\the\numexpr#2+1\relax\fi% ROUNDED
% #2% TRUNCATED
\fi%% \fi%
}
\begin{document}
1. \makebox[.8in][r]{9.421715604} to 5 digits: \myTruncatingFloatingPoints{5}{9.421715604}
2. \makebox[.8in][r]{9.421715604} to 3 digits: \myTruncatingFloatingPoints{3}{9.421715604}
3. \makebox[.8in][r]{9.421715604} to 1 digits: \myTruncatingFloatingPoints{1}{9.421715604}
4. \makebox[.8in][r]{9.421715604} to 0 digits: \myTruncatingFloatingPoints{0}{9.421715604}
5. \makebox[.8in][r]{29} to 2 digits: \myTruncatingFloatingPoints{2}{29}
6. \makebox[.8in][r]{.1275} to 3 digits: \myTruncatingFloatingPoints{3}{.1275}
7. \makebox[.8in][r]{.1275} to 4 digits: \myTruncatingFloatingPoints{4}{.1275}
8. \makebox[.8in][r]{$-$.12} to 6 digits: \myTruncatingFloatingPoints{6}{-.12}
\end{document}