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.
There are some problems with this objective:
1. double is incapable of exactly representing most two decimal place
numbers.
If the numbers that have specific numbers of digits after the decimal
point are particularly important in your application, you should
probably be using BigDecimal, not double.
2. Even if it is just a matter of output formatting, you should use
DecimalFormat rather than doing the rounding yourself. If you need very
specific control over the rounding, convert to BigDecimal and pick from
its collection of rounding modes.
Effectively, you have set yourself a very artificial problem by saying
what features can be used.
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;
Although you can write multiple variable declarations for the same type
in one declaration, it gets a bit muddled unless the declarations are
VERY simple. It also tends to discourage writing long identifiers and/or
comments explaining what the variables mean.
In each case, first pick a really meaningful name for each variable. If
that fully explains what it is about, fine. If not, write a comment
adding whatever information is not in the name.
The conversion to int here will overflow to Integer.MAX_VALUE if
decimalNumber is 9 or greater. If the conversion is just intended to
ensure that the result is an integer, it adds nothing to what is
guaranteed by the API documentation for Math.pow:
"If both arguments are integers, then the result is exactly equal to the
mathematical result of raising the first argument to the power of the
second argument if that result can in fact be represented exactly as a
double value."
I'm not going to write any more until you replace the identifiers "a"
and "b" with meaningful identifiers, with comments if necessary, so that
you tell me what they are for, rather than me trying to guess from how
you use them.
Patricia