Skip to content
Prev 302256 / 398503 Next

Formatting numbers for display

HI,

I modified the code, thanks to Tejas.? Now, the results look like
fun1<-function(x)
?ifelse(x>10^7,gsub("\\d)[.].*","\\1",x),ifelse(x<10^7 & x>1,formatC(x,width=length(x),format="fg",digits=8,flag="",drop0trailing=FALSE),sprintf("%.3f",x)))

fun1(VALUES)
?[1] "123456789"??? "12345678"???? "?? 1234567.9" "?? 123456.89" "?? 12345.789"
?[6] "?? 1234.6789" "?? 123.56789" "?? 12.456789" "?? 1.3456789" "0.123"?????? 
[11] "0.012"??????? "0.001"??? 

David's code:
? form3 <- function (x) switch(findInterval(x, c( 0, 1, 10^7, Inf)), 
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? format(x, digits=3), 
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? formatC(x, width=8, ?format="f", ? 
drop0trailing=FALSE), 
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? trunc(x) ) 
?sapply(VALUES,form3)
?[1] "123456789"??? "12345678"???? "1234567.9000" "123456.8900"? "12345.7890"? 
?[6] "1234.6789"??? "123.5679"???? " 12.4568"???? "? 1.3457"???? "0.123"?????? 
[11] "0.0123"?????? "0.00123"

#Modfied form3 a little:
form3 <- function (x) switch(findInterval(x, c( 0, 1, 10^7, Inf)),
????????????????????????????????????? formatC(x, width=8, format="f",digits=3),
????????????????????????????????????? formatC(x, width=8,? format="f",? 
drop0trailing=TRUE,flag="0"),
????????????????????????????????????? trunc(x) ) 
sapply(VALUES,form3)
?[1] "123456789" "12345678"? "1234567.9" "123456.89" "12345.789" "1234.6789"
?[7] "123.5679"? "012.4568"? "001.3457"? "?? 0.123"? "?? 0.012"? "?? 0.001" 

Still, there needs improvement.
? ? 
A.K.

?

----- Original Message -----
From: David Winsemius <dwinsemius at comcast.net>
To: Dennis Fisher <fisher at plessthan.com>
Cc: arun <smartpink111 at yahoo.com>; R help <r-help at r-project.org>
Sent: Friday, August 3, 2012 3:14 AM
Subject: Re: [R] Formatting numbers for display
On Aug 2, 2012, at 8:27 PM, arun wrote:

            
I didn't get the same results as requested with a wider variety of tests using those formatting methods. Here's what I could offer:

form3 <- function (x) switch(findInterval(x, c( 0, 1, 10^7, Inf)),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?  format(x, digits=3),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?  formatC(x, width=8,? format="f", drop0trailing=FALSE),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?  trunc(x) )

tx <- c( 0.55555555, 55.555555555, 555555555555555.55555555)
[1] "0.556"? ? ? ? ?  " 55.5556"? ? ?  "555555555555555"

(Still not getting the 8 digits in the intermediate value cases. Have not figured out how to get rid of leading space.)

--David.
Using the vector of long 5's
[1] "0.556"? ? ? ? ?  "00055.56"? ? ? ? "555555555555556"
David Winsemius, MD
Heritage Laboratories
West Hartford, CT