Question:
How to round decimals to whole number, without using the Math.round or ceiling program?
Answer:
You can do it with casting.
Code:
import java.util.Scanner; public class Rounding { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter double: " ); Double d = scan.nextDouble(); System.out.println("You entered: " + d); Integer i = d.intValue(); if ( d - i >= .5 ) { i=i+1; } System.out.println("Rounded: " + i); } }
Output:
$ java Rounding Enter double: 12.4999 You entered: 12.4999 Rounded: 12 $ java Rounding Enter double: 8.5 You entered: 8.5 Rounded: 9