4

I am currently having trouble achieving the desired rounding of numbers using knitr. The issue occurs with numbers that would end with a zero on the final rounded digit. An example of this is 14.04, which I want to be rounded at 1 decimal place to 14.0. The issue is that knitr with latex as the output gives 14 without the 0 as the decimal place.

I would assume that there is some sort of trailing zero option, but I cannot locate it. Any ideas? Bellow is a short minimal working example of the issue.

\documentclass[12pt]{article}
\begin{document}

<<>>=
library(knitr)
options(digits=1)
@

Full number = 14.0417

Number of issue \Sexpr{14.041783}

Should appear as 14.0

\end{document}

EDIT: While looking at the first answer (Thanks for the rapid reply Ben), I realised the other issue that I have here. While solutions where the number is formatted as a string, get around the main issue, they do not solve the same issue when it occurs on "large" numbers, which become formatted using scientific notation.

I will give a second example that demonstrates this: say the number is 100,400,000. The resulting output using options(digits=2) becomes 10^8, where I would prefer 1.04 x 10^8. Rnw example below.

\documentclass[12pt]{article}
\begin{document}

<<>>=
library(knitr)
options(digits=2)
@
Number 100,400,000 

\Sexpr{100400000}

\end{document}
pmgurman
  • 41
  • 2
  • Not exactly what you asked for, but it's worth reading about functions for formatting numbers on this question http://stackoverflow.com/q/5812493/134830 – Richie Cotton Dec 14 '15 at 05:57
  • Regarding your edit: Also not exactly what you asked for, but what about `sprintf("%1.3e", 100400000)` which gives `1.004e+08`? You should read `?sprintf`. – CL. Dec 15 '15 at 16:15

1 Answers1

2

I think this answers it: use sprintf().

\documentclass[12pt]{article}
\begin{document}

<<>>=
library(knitr)
options(digits=1)
x <- 14.0417
@


Full number = \Sexpr{x}

Number of issue \Sexpr{sprintf("%.1f",x)}
\end{document}

Output

Community
  • 1
  • 1
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Thanks for the rapid reply. I have added a bit of further explanation of the issue above, which I only realised once I read your solution. – pmgurman Dec 14 '15 at 07:19