Search code examples
rformattingscientific-notation

Control the number of decimals in scientific notation


I have a vector:

c(0, 1.23, 0.0000123)

and I would like to get scientific notation defining the number of decimals. Something like:

# [1] 0.000e+00 1.230e+00 1.230e-05

or like:

# [1] 0.000000e+00 1.230000e+00 1.230000e-05

How can I do that?


Solution

  • From my comment:

    Let

    x <- c(0, 1.23, 0.0000123)
    

    and try

    sprintf("%.3e", x)
    [1] "0.000e+00" "1.230e+00" "1.230e-05"
    

    If you don't want the quotes and the [1] to be displayed then do this

    cat(sprintf("%.3e", x),"\n")
    0.000e+00 1.230e+00 1.230e-05