Question

I am using sprintf to output a number. The number can be an integer or a float.

For some reason, I need to keep three digits after the decimal point if the number is a float, while directly output the integer.

For example, if the number is 3, then it should output 3. If the number is 3.333333, then it should output 3.333. How can I format the string using sprintf(), or are there any other ways?

Was it helpful?

Solution 2

You could do a conditional formatting:

f <- function(x) sprintf(ifelse(is.integer(x),"%i", "%.3f"), x)

If it is integer:

f(3L)
[1] "3"

If it is floating point:

f(3.3333333)
[1] "3.333"

OTHER TIPS

The answer from Carlos Cinelli is really good and elegant. It is correct as it tests if the actual data type is integer or not. But if shapeare wants to test only if the number is a "whole number", that is, without decimal places, the following solution might be better:

is.wholenumber <- function(x, tol = .Machine$double.eps^0.5)  abs(x - round(x)) < tol
f <- function(x) sprintf(ifelse(is.wholenumber(x),"%i", "%.3f"), x)

This way, if it is a whole number (aka integer):

f(3)
[1] "3"

I've got the wholenumber function from an example on help page for is.integer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top