The function formatC() produces wrong formats of numbers when a simple arithmetic operation is passed as x.
Example:
formatC(29, width = 3, format = "d", flag = "0")
> "029"
This is correct. But when I do:
formatC(100*0.29, width = 3, format = "d", flag = "0")
> "028"
What am I missing here? (R version 4.3.2 (2023-10-31 ucrt))
>Solution :
You are using format = "d". The docs set out the various options for the format argument:
equal to
"d"(for integers),"f","e","E","g","G","fg"(for reals), or"s"(for strings). Default is"d"for integers,"g"for reals.
Neither 29 nor 0.29 * 100 are stored by R as an integer and they are not equal. You can see this here:
class(29) # numeric
class(29L) # integer
sprintf("%.20f", 29)
# [1] "29.00000000000000000000"
sprintf("%.20f", 100 * 0.29)
# [1] "28.99999999999999644729"
Using integer formatting is truncating the second value to 28. Use an appropriate format for reals e.g.:
formatC(100 * 0.29, width = 3, format = "g", flag = "0")
# [1] "029"
For more on why this occurs see: Why are these numbers not equal?