Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping a large number of zeros being printed (not scientific notation)

What I'm trying to achieve is to have all printed numbers display at maximum 7 digits. Here are examples of what I want printed:

0.000000 (versus the actual number which is 0.000000000029481.....)

0.299180 (versus the actual number which is 0.299180291884922.....)

I've had success with the latter types of numbers by using options(scipen=99999) and options(digits=6). However, the former example will always print a huge number of zeros followed by five non-zero digits. How do I stop this from occurring and achieve my desired result? I also do not want scientific notation.

I want this to apply to ALL printed numbers in EVERY context. For example if I have some matrix, call it A, and I print this matrix, I want every element to just be 6-7 digits. I want this to be automatic for every print in every context; just like using options(digits=6) and options(scipen=99999) makes it automatic for every context.

like image 664
Jase Avatar asked Dec 29 '12 09:12

Jase


2 Answers

You can define a new print method for the type you wish to print. For example, if all your numbers are doubles, you can create

print.double=function(x){sprintf("%.6f", x)}

Now, when you print a double (or a vector of doubles), the function print.double() will be called instead of print.default().

You may have to create similar functions print.integer(), print.complex(), etc., depending on the types you need to print.

To return to the default print method, simply delete the function print.double().

like image 141
Robin Ryder Avatar answered Oct 17 '22 10:10

Robin Ryder


Are all your numbers < 1? You could try a simple sprintf( "%.6f", x ). Otherwise you could try wrapping things to sprintf based on the number of digits; check ?sprintf for other details.

like image 3
Kevin Ushey Avatar answered Oct 17 '22 12:10

Kevin Ushey