Setting default number of decimal places for printing
You could do this:
print <- function(x, ...) {
if (is.numeric(x)) base::print(round(x, digits=2), ...)
else base::print(x, ...)
}
Printing the correct number of decimal points with cout
With <iomanip>
, you can use std::fixed
and std::setprecision
Here is an example
#include <iostream>
#include <iomanip>
int main()
{
double d = 122.345;
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << d;
}
And you will get output
122.34
Default Number of Decimal Places to Output in PHP
And when you can't rely on the PHP configuration, don't forget about number_format() which you can use to define how a number is returned, ex:
// displays 3.14 as 3 and 4.00 as 4
print number_format($price, 0);
// display 4 as 4.00 and 1234.56 as 1,234.56 aka money style
print number_format($int, 2, ".", ",");
PS: and try to avoid using money_format(), as it won't work on Windows and some other boxes
Controlling number of decimal digits in print output in R
The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options
value as a default.
As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.
Mathematica or Maple will allow you to give as many decimal places as your heart desires.
EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.
On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin
(usually 2e-308).
Compare these two analyses.
x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1) #Should throw an error
x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2) #ok
In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.
As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr
package.
mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")
These are slower and more memory intensive to use than regular (double precision) numeric
vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.
Formatting Decimal places in R
Background: Some answers suggested on this page (e.g., signif
, options(digits=...)
) do not guarantee that a certain number of decimals are displayed for an arbitrary number. I presume this is a design feature in R whereby good scientific practice involves showing a certain number of digits based on principles of "significant figures". However, in many domains (e.g., APA style, business reports) formatting requirements dictate that a certain number of decimal places are displayed. This is often done for consistency and standardisation purposes rather than being concerned with significant figures.
Solution:
The following code shows exactly two decimal places for the number x
.
format(round(x, 2), nsmall = 2)
For example:
format(round(1.20, 2), nsmall = 2)
# [1] "1.20"
format(round(1, 2), nsmall = 2)
# [1] "1.00"
format(round(1.1234, 2), nsmall = 2)
# [1] "1.12"
A more general function is as follows where x
is the number and k
is the number of decimals to show. trimws
removes any leading white space which can be useful if you have a vector of numbers.
specify_decimal <- function(x, k) trimws(format(round(x, k), nsmall=k))
E.g.,
specify_decimal(1234, 5)
# [1] "1234.00000"
specify_decimal(0.1234, 5)
# [1] "0.12340"
Discussion of alternatives:
The formatC answers and sprintf answers work fairly well. But they will show negative zeros in some cases which may be unwanted. I.e.,
formatC(c(-0.001), digits = 2, format = "f")
# [1] "-0.00"
sprintf(-0.001, fmt = '%#.2f')
# [1] "-0.00"
One possible workaround to this is as follows:
formatC(as.numeric(as.character(round(-.001, 2))), digits = 2, format = "f")
# [1] "0.00"
How to print a float with 2 decimal places in Java?
You can use the printf
method, like so:
System.out.printf("%.2f", val);
In short, the %.2f
syntax tells Java to return your variable (val
) with 2 decimal places (.2
) in decimal representation of a floating-point number (f
) from the start of the format specifier (%
).
There are other conversion characters you can use besides f
:
d
: decimal integero
: octal integere
: floating-point in scientific notation
Change default float print format
You are not allowed to monkeypatch C types, like Ignacio said.
However, if you are terribly pressed in doing so and you know some C, you could go modify the Python interpreter source code yourself, then recompile it into a custom solution. Once I modified one of the standard behaviors for lists and it was only a moderate pain.
I suggest you find a better solution, such as just printing the floats with the "%0.2f"
printf notation:
for item in mylist:
print '%0.2f' % item,
or
print " ".join('%0.2f' % item for item in mylist)
Why do print and printf show different numbers of decimal places by default
This is due to the fact that by default for double or float
printf
print number upto 6 decimal places. You need to specify the precision if you want to control how many decimal places you want to print via printf
. System.out.println
prints exact value of double/float without adding some default decimal points.
e.g.
double d = 1.0;
// it will print 1.000000
System.out.printf("%f\n", d);
//1.0
System.out.printf("%.1f", d);
//1.0
System.out.println(d);
Related Topics
How to Fill in the Contour Fully Using Stat_Contour
Object.Size() Reports Smaller Size Than .Rdata File
R: Split Elements of a List into Sublists
R: Serialize Objects to Text File and Back Again
R Return the Index of the Minimum Column for Each Row
Using Mean with .Sd and .Sdcols in Data.Table
Generating Names Iteratively in R for Storing Plots
Save Output Between Pipes in Dplyr
Retrieve Census Tract from Coordinates
Keyboard Shortcut for Inserting Roxygen #' Comment Start
Generating a Very Large Matrix of String Combinations Using Combn() and Bigmemory Package
Subsetting a Data.Table by Range Making Use of Binary Search
Evaluate Inline R Code in Rmarkdown Figure Caption
Multiply Columns in a Data Frame by a Vector
How to Make Discrete Gradient Color Bar with Geom_Contour_Filled