Search code examples
rfractions

Convert decimals to number and fraction


How can I convert decimal answers, e.g. 3353/6 into 558 5/6?

fractions(3353/6) gets me 558.8333 but not in the fraction term. Is there any in-built function for this purpose?


Solution

  • This function does the basic calculation you need:

    nicefrac <- function(x) {
       f <- attr(MASS::fractions(x), "fracs") ## extract string representation
       s <- as.numeric(strsplit(f, "/")[[1]])
       res <- c(whole = s[1] %/% s[2], num = s[1] %% s[2], denom = s[2])
       res
    }
    
    x <- 3353/6
    nicefrac(x)
    ## whole   num denom 
    ##   558     5     6 
    

    Depending on how you want to print/represent this, you could (1) leave it as-is; (2) use sprintf("%d %d/%d", nicefrac[1], nicefrac[2], nicefrac[3]) to convert to a string representation; (3) write a little S3 class with a print method that does what you want (modifying MASS:::print.fractions).