ThetaFC
ThetaFC

Reputation: 670

How to control number of digits in exponent with sprintf in R?

This R code produces the following:

> sprintf("%.6e", c(5, 50, 500, 5000))
[1] ""5.000000e+00" "5.000000e+01" "5.000000e+02" "5.000000e+03"

But I would like to have three digits in the exponent (after the "e+") like this:

"5.000000e+000" "5.000000e+001" "5.000000e+002" "5.000000e+003"

Upvotes: 1

Views: 362

Answers (1)

akrun
akrun

Reputation: 887078

Here, is an option with sub after making the changes with sprintf to insert 0 before the last element in the string after the sprintf formatting

sub('([0-9])$', '0\\1',  sprintf("%.6e", c(5, 50, 500, 5000)))
#[1] "5.000000e+000" "5.000000e+001" "5.000000e+002" "5.000000e+003"

Upvotes: 1

Related Questions