M
man4*.*
example: write a function which will given decimal number round for a
specific number of decimals.
Function has a 2 input parameters(dec. number and number of decimals) and
returns rounded decimal
value. For rounding we can use only int function or similar.
I've pasted my soulution, so please tell me what do you think abut it..give
some advices
my solution:
public class Rounding {
public static double round(double number, int decimalNumber){
int a=(int)Math.pow(10, decimalNumber+1),
b=(int)((number*a)%a)%10;
if (b<5){
double temp=number*a/10;
int temp2=(int)temp;
number=(double)temp2/(a/10);
}
else {
double temp=number*a/10;
int temp2=(int)temp+1;
number=(double)temp2/(a/10);
}
return number;
}
public static void main (String[] args){
double x=7.12345654;
int decimalNumber=4;
System.out.println("Round number:\n"+x+" at "+decimalNumber+" decimals");
System.out.println(round(x,decimalNumber));
}
}
specific number of decimals.
Function has a 2 input parameters(dec. number and number of decimals) and
returns rounded decimal
value. For rounding we can use only int function or similar.
I've pasted my soulution, so please tell me what do you think abut it..give
some advices
my solution:
public class Rounding {
public static double round(double number, int decimalNumber){
int a=(int)Math.pow(10, decimalNumber+1),
b=(int)((number*a)%a)%10;
if (b<5){
double temp=number*a/10;
int temp2=(int)temp;
number=(double)temp2/(a/10);
}
else {
double temp=number*a/10;
int temp2=(int)temp+1;
number=(double)temp2/(a/10);
}
return number;
}
public static void main (String[] args){
double x=7.12345654;
int decimalNumber=4;
System.out.println("Round number:\n"+x+" at "+decimalNumber+" decimals");
System.out.println(round(x,decimalNumber));
}
}