Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

How would you round a double to a certain decimal?

+10 votes
asked Sep 13, 2016 in CSC 211 (F16) by Ryan Philp (702 points)

2 Answers

+2 votes

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 Minh Ta (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 Jon Clauss (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.