Re: rounding decimals




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

.



Relevant Pages

  • Re: rounding decimals
    ... specific number of decimals. ... For rounding we can use only int function or similar. ... DecimalFormat rather than doing the rounding yourself. ... I'm not going to write any more until you replace the identifiers "a" ...
    (comp.lang.java.programmer)
  • Re: <= 0
    ... Int is a function to convert a value to its whole number part ... What if the data type has to be Double, Fixed, 4 Decimals? ... "The form control for UnitCount is Fixed with 0 decimal points. ...
    (microsoft.public.access.formscoding)
  • Re: How do I show only the whole number w/o eliminating four decim
    ... Actually if the OP needs to do this it is better to use TRUNC since ... INT will round down to the nearest integer, ... the decimals. ...
    (microsoft.public.excel.worksheet.functions)
  • Re: How do I show only the whole number w/o eliminating four decim
    ... Good point Peo. ... INT will round down to the nearest integer, ... like -123,478.99 will return -123,479 with INT and -123,478 with TRUNC ... the decimals. ...
    (microsoft.public.excel.worksheet.functions)
  • Re: RtlMoveMemory to read an integer from a file
    ... You can also use a BinaryReader's ReadInt32 or ReadInt16 method if you need ... to read an int. ... > *This will round to 0 decimals. ... > set decimals to (VariableDecimals) ...
    (microsoft.public.dotnet.languages.csharp)

Loading