2
votes

If you declare a numeric vector with a mix of decimal and integer values and print it, all of them are converted to a decimal number.

s <- c(0, 1.1, 2, 3)
print(s)
[1] 0.0 1.1 2.0 3.0

but if you use cat instead of print, each number is formatted according to its type.

cat(s, sep=" ")
0 1.1 2 3 

How can you print a numeric vector using cat but converting the values to decimal numbers as print does?

Best

2

2 Answers

3
votes

You can use format:

cat(format(s,digits=2))
9
votes

for example:

> cat(sprintf("%.01f", s))
0.0 1.1 2.0 3.0