Math.floor may be used to round a number to a specific decimal place. For exampl
ID: 3620491 • Letter: M
Question
Math.floor may be used to round a number to a specific decimal place. For example, the statement:y = Math.floor( x * 10 + .5 ) / 10;
rounds x to the tenths position (i.e., the first position to the right of the decimal point). And the statement:
y = Math.floor( x * 100 + .5 ) / 100;
rounds x to the hundredths position (i.e., the second position to the right of the decimal point). Write a program that defines three methods to round a number x in various ways:
roundToTenths(number)
roundToHundredths(number)
roundToThousandths(number)
Incorporate the previous methods into a program that reads a real number and then displays the number rounded to the nearest tenth, the number rounded to the nearest hundredth and the number rounded to the nearest thousandth.
Explanation / Answer
please rate - thanks import java.util.*;public class main
{public static void main(String[] args)
{Scanner in=new Scanner(System.in);
double num;
System.out.print("Enter a real number: ");
num=in.nextDouble();
System.out.println(num+" rounded to the nearest tenths is "+roundToTenths(num));
System.out.println(num+" rounded to the nearest hundredths is "+roundToHundredths(num));
System.out.println(num+" rounded to the nearest thousandths is "+roundToThousandths(num));
}
public static double roundToTenths(double n)
{return Math.floor( n * 10 + .5 ) / 10;
}
public static double roundToHundredths(double n)
{return Math.floor( n * 100 + .5 ) / 100;
}
public static double roundToThousandths(double n)
{return Math.floor( n * 1000 + .5 ) / 1000;
}
}