Question:
How can you round doubles to the nth decimal?
Answer:
For 5 digits precision:
(double)Math.round(value * 100000) / 100000The number of zeros indicate the number of decimals.
Code:
public class Rounding { public static void main(String[] args) { double pi = 3.14159265359; System.out.println(pi); System.out.println( Math.round(pi) ); System.out.println( (double)Math.round(pi*10)/10 ); System.out.println( (double)Math.round(pi*100)/100 ); System.out.println( (double)Math.round(pi*1000)/1000 ); System.out.println( (double)Math.round(pi*10000)/10000 ); System.out.println( (double)Math.round(pi*100000)/100000 ); System.out.println( (double)Math.round(pi*1000000)/1000000 ); System.out.println( (double)Math.round(pi*10000000)/10000000 ); } }
Output:
$ java Rounding 3.14159265359 3 3.1 3.14 3.142 3.1416 3.14159 3.141593 3.1415927