質問

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?

役に立ちましたか?

解決 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"

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top