Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use formatC so that numbers as a result of a simple arithmetic operation are correct?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading