# How would you round a double to a certain decimal?

There's a statement called printf that is a little bit more advance to use.
Here is its syntax:

double number = 0.8123512512;

System.out.printf("%0.3f", number);

The console will display: 0.812

The % starts the whole thing, the 3 right after the period indicates that it only print out 3 decimal numbers, the "f" character stands for float type, which is kinda the same as double. The "number" after the comma stand for displaying the variable number in that blank.

answered Sep 14, 2016 by (1,045 points)
+1 vote
One way would be to use Math.floor.

For example to round x = 3.1415926 to the nearest hundredths

(Math.floor(x * 100))/100    // so first you have to multiply by the place you want to round to
// then you use the floor function [see Sec 3.2]
// then you divide back to turn it back into a decimal

To the nearest 10,000th

(Math.floor(x * 10000))/10000    // careful not to use commas, I think.

Course there might be a better way...
answered Sep 14, 2016 by (100 points)
My bad: Math.floor will truncate, not round.

(Math.round(x * 1000))/1000.

works. It seems that you have to be sure to divide by a double to avoid integer division.