############################################################## # # R FUNCTION "DECIMAL", TO OUTPUT A REAL NUMBER TO A SPECIFIED # NUMBER OF DECIMAL POINTS INCLUDING TRAILING ZEROES. # # BY JEFFREY S. ROSENTHAL (www.probability.ca), January 2025 # # USAGE: decimal(r,i) to output the real value r with i decimal points. # # FLAGS: per=TRUE to write as percentage and append "%" # texper=TRUE to write as percentage and append "\\%" # (for inclusion in a tex document) # # EXAMPLES: # decimal(5.31, 1) ## Returns "5.3" # decimal(5.31, 4) ## Returns "5.3100" # decimal(0.531, 2, per=TRUE) ## Returns "53.10%" # decimal(0.531, 2, texper=TRUE) ## Returns "53.10\\%" decimal = function(x, numdec=1, per=FALSE, texper=FALSE) { if (per || texper) xx = x * 100.0 else xx = x check.integer = function(xx) {abs(xx - round(xx)) < 10^(-8)} extratext = "" if (check.integer(xx) && (numdec >= 1) ) extratext = "." for (d in 1:floor(numdec)) { if (check.integer(xx * 10^(d-1))) extratext = paste(extratext, "0", sep="") } if (texper) extratext = paste(extratext, "\\%", sep="") else if (per) extratext = paste(extratext, "%", sep="") return(paste(round(xx,numdec), extratext, sep="")) }