Re: rounding decimals
- From: su_dang@xxxxxxxxxxx
- Date: 6 Oct 2006 07:52:18 -0700
man4*.* wrote:
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));
}
}
Not sure if it is the answer you are looking for, but the
java.math.BigDecimal and java.math.MathContext classes might help
.
- References:
- rounding decimals
- From: man4*.*
- rounding decimals
- Prev by Date: Generate 2d images on the fly
- Next by Date: is it possible to make superclass extend another class ?
- Previous by thread: Re: rounding decimals
- Next by thread: Re: rounding decimals
- Index(es):
Relevant Pages
|
Loading