Question:
How can you round doubles to the nth decimal?
Answer:
Using the Math.round method and formating with the DecimalFormat class.
Code:
import java.text.DecimalFormat; public class RoundDoubles { public static void main(String[] args) { double d1 = 0; double d2 = 1.49999; double d3 = 3.14159265359; double d4 = 98.5555555; //the number of zeros indicate the number of decimals. d1 = (double)Math.round(d1 * 100) / 100; d2 = (double)Math.round(d2 * 100) / 100; d3 = (double)Math.round(d3 * 100) / 100; d4 = (double)Math.round(d4 * 100) / 100; //the number of .0's indicate right padding. DecimalFormat df = new DecimalFormat("0.00"); System.out.println(df.format(d1)); System.out.println(df.format(d2)); System.out.println(df.format(d3)); System.out.println(df.format(d4)); } }
Output:
$ java RoundDoubles 0.00 1.50 3.14 98.56