Multiply percantage values - java

I need to multiply a double value by 12%, how can I do so?
public class AnnualMaintenanceFee {
public void GetTotal(int TotalND) {
double software=1500;
double TNDWithSof= 1500+TotalND;
double AMF= TNDWithSof 12;
System.out.println("New Total: "+AMF);
}
}

Simply do this,
double AMF= TNDWithSof * 0.12; // 0.12 means 12/100(12%), you can use 0.12 directly
System.out.println("New Total: "+AMF);

Here you go :
(yourDouble * 12) / 100

The % in 12% is no more than an operator that divides by 100 (or equivalently from a mathematical perspective, multiplies by 0.01).
So 12% can be written as 12 * 0.01. I prefer that to writing 12 / 100 since the latter, unless you're careful, will be performed in integer division with any fractional part being discarded.
Do consider using a currency type though for money values: floating point numbers are not designed to represent exact money amounts.

For multiplication use *, for percent 12% you can use 12/100 like:
double AMF= TNDWithSof*(12/100);
System.out.println("New Total: "+AMF);
Because the division(12/100) be evaluated in first because it's inside bracket, and finally evaluate TNDWithSof*0.12.

Related

Method involving math giving different answer than calculator

I'm new to java so please bear with me. I'm trying to get the percentage of wins from total number of games and something I'm doing is way off. My method for getting the percentage is below:
public double winPercentage(int wins, int total)
{
return (wins % total) * 1.00;
}
If I win 52 games out of 254 my answer comes up to 52.0, using my calculator that same answer is 20.47 assuming wins/total*100. If I switch the modulus to / I constantly get 0.0
I've tried a variation of different decimal places and order of operations. I can't seem to get the calculator and method to match up.
The percent sign in wins % total has no relationship to computing a percentage.
To compute percentage in Java, you could write
return 100.0 * wins / total;
Here, 100.0 serves dual purpose:
it rescales the result to percentage points;
it turns the subsequent division into a floating-point one (without which it's an integer division, always returning zero when wins < total).
Java uses % as modulo operator, so it will always return the remainder as a result not percentage.
If we divide integer by integer, then result will not be precise as required for percentage function. E.g. if we try to divide 52 by 254 result will be 0 for an integer not 0.2047, as integer is capable of holding complete numbers only. So to get percentage, you can use double/float as parameter data type like below instead of integer. 
public double winPercentage(double wins, double total) {
return wins / total * 100;
}

Floating point precision with Math.Ceil (Java)

I'm implementing a business rule to calculate a percentage increase on a stock level:
Stock level | Percentage Increase | Expected output
100 | 93 | 193
As decimal stock levels are not well defined the rule is to round up the output:
public int calculateStockLevel(int rawStockLevel, double percentageIncrease) {
return Math.ceil(rawStockLevel * (1 + (percentageIncrease / 100));
}
Actual output for the situation above: 194 (The test fails)
This looks like a floating point precision error, whats an elegant & readable way to get this test to pass?
You should use BigDecimal to specify what precision you want, but for your case you could do something simpler: just divide by 100 at the end.
public int calculateStockLevel(int rawStockLevel, double percentageIncrease) {
return Math.ceil(rawStockLevel * (100 + percentageIncrease) / 100);
}
Binary floating-point types can't represent exactly every value in decimal. So percentageIncrease / 100 will get the closest representation in binary. In your case the exact value of 0.93 in double precision is 0.930000000000000048849813083507, which is slightly more than the true decimal value. Therefore after ceil it'll be rounded up to 0.94
If you want exact decimal output you must use decimal arithmetic, like BigDecimal. But in your case you can just do it in plain integer, utilizing the fact that the fractional part of the result must be larger than 0 if remainder of the division is non-zero.
int temp = rawStockLevel * (100 + percentageIncrease);
int result = temp/100;
if (temp % 100 != 0)
result++; // round up if not divisible by 100
return result;

How to round to the nearest 0.05? [duplicate]

This question already has an answer here:
Java rounding to nearest 0.05
(1 answer)
Closed 8 years ago.
I'm trying to find a way on how to round to the nearest 0.05 in java. Let's say that I have the following numbers:
0.33
0.02
0.874
0.876
This should become:
0.35
0.00
0.85
0.90
I tried many things and I can only get it to round to n places behind the comma by using BigDecimal, but I can't seem to find a way for this one.
Can someone help me?
EDIT: Thank you for all your help, I am amazed at how easy this could be done. And how do I get the double converted into a string properly? I can't use Double.toString(double d) because for example the string will be "0.9" instead of "0.90"?
0.05 == 1/20, right? Therefore, what you need is just the nearest number with dividing by 1/20, so, you may multiply this number by 20, get the nearest number with dividing by 1, then get the initial things.
TL;DR: you just may just multiply it by 20, round and divide by 20 again:
public double customRound(double num) {
return Math.round(num * 20) / 20.0;
}
A simple way would be:
double d = 0.33;
double roundedTimes20 = Math.round(d * 20);
double rounded = roundedTimes20 / 20; //0.35
but note that the resulting double is not necessarily the exact representation of the rounded number (usual floating point caveat) and that the method assumes that your original double times 20 can fit in a long.
Try a function:
public static double round05(double num) {
return Math.round(num * 20) / 20.0;
}
You can use String.format to format value to String
String s = String.format("%.2f", 0.9);

parseDouble of Double class adds extra zero

public static double centsToDollars(Number cents, int precision) {
return BigDecimal.valueOf(cents.doubleValue() / 100).setScale(precision, RoundingMode.DOWN).doubleValue();
}
Code above works completely fine when I want to display cents value in dollars. For example, for 1 cent, it returns 0.01 dollar.
assertEquals("$0.01", FormatUtils.centsToDollars(1, 3))
assertEquals("$0.012", FormatUtils.centsToDollars(1.2345, 3))
assertEquals("$0.327", FormatUtils.centsToDollars(32.7, 3))
But I can't figure out, why FormatUtils.centsToDollars(0.65, 3) returns $0.0060. I expect to receive 0.006 instead. What is the latest zero about ?
Update
Looks like the root cause of the issue is invocation of doubleValue() of BigDecimal
System.out.println(Double.parseDouble("0.006"));
System.out.println(BigDecimal.valueOf(0.006).doubleValue());
returns 0.0060 for me
Any clue why this happens ?
parseDouble of Double class adds extra zero
There is a bug id:4428022 in Java 1.4 to 6 which means it adds an extra zero you don't need. This happens for values 0.001 to 0.009 only. Java 7 doesn't have this bug.
for (int i = 1; i <= 9; i++)
System.out.println(i / 1000.0);
in Java 6 prints
0.0010
0.0020
0.0030
0.0040
0.0050
0.0060
0.0070
0.0080
0.0090
but in Java 7 prints
0.001
0.002
0.003
0.004
0.005
0.006
0.007
0.008
0.009
I suspect that 0.65 is actually slightly less in reality. When you divide it by 100 you get something like 0.006499999999999 which when rounded drops to 0.006
I suspect what you wanted was
public static String centsToDollars(Number cents, int precision) {
return "$" + BigDecimal.valueOf(cents.doubleValue())
.divide(BigDecimal.valueOf(100))
.setScale(precision, RoundingMode.HALF_UP);
}
Try
System.out.println(new BigDecimal(0.65 / 100));
This is how I would write it
public static String centsToDollars(double cents) {
double rounded = Math.round(cents * 100) / 1e4;
return "$" + rounded;
}
This assumes two decimal places of cents.
parseDouble of Double class adds extra zero
No it doesn't. The methods you are using to format the double is doing that. Doubles don't contain trailing decimal zeros. They don't contain decimal anything.

unexpected results with decimal arithmetic expression

I have some business logic with arithmetic expression and their results are as follows
(10.0 * 20.58)/1.0=205.7999..98
(6.0 * 37.9)/1.0=227.3999..98
(5.0 * 50.0)/1.0=250.0
(10.0 * 37.9)/1.0=379.0
But expected results are
(10.0 * 20.58)/1.0=205.8
(6.0 * 37.9)/1.0=227.4
(5.0 * 50.0)/1.0=250.0
(10.0 * 37.9)/1.0=379.0
I am not clear why we are getting that .999..98 fraction part? Due to that my equals comparison is failing and so business logic. For few cases we are using
amt = (double)Math.round(orderAmt*100000)/100000;
But that is not possible to do the same in each and every place where we have double arithmetic expression.
I want to know why we get such results randomly and is there any possibility to round the results to 5 decimal places instead of rounding every where?
With radix 10 there are some fractions who can't be expressed exactly with a finite number of digits, like for example 1/3 = 0.33333333....
It's the same with radix 2, except that the dividers that produce this kind of results are not the one we are accustomed to, and for example, for 20.58, which is 2058 / 100, it is the case.
Internally, doubles and floats are stored with bits (an not digit), so the exact value of the double or float just can't be stored in the computer's memory. Each time you perform an operation with this value, you get a small shift, because of the approximation, which becomes visible when converting back to decimal format for printing.
It's something you have to pay attention while perfoming computations where precision is important.
So you have two solutions:
Store all your numbers in decimal type and perform all your calculation with it. This will achieve accuracy but for the price of performance.
You can also keep all the calculation with double or float, and format with a fixed number of digits only for printing results.
You could use BigDecimal for roundoff
BigDecimal bd = new BigDecimal((10.0 * 20.58)/1.0) ;
bd = bd.setScale(4, RoundingMode.UP);
use with a static method
public static double round(double value, int digits) {
BigDecimal bd = new BigDecimal(value);
return bd.setScale(digits, RoundingMode.UP).doubleValue();
}
RoundingMode has :
RoundingMode.UP;
RoundingMode.DOWN;
RoundingMode.HALF_DOWN;
RoundingMode.HALF_EVEN;
The basic problem is that
System.out.println(10.0 * 20.58);
prints
205.79999999999998
has a small rounding error due to a representation error in 20.58
You either need to
round the result before comparing.
use a comparision which allows for some error
use BigDecimal (which is over kill in most cases)
use cents instead of dollars i.e. use int or long with fixed precision.
In the last case, the same operation would read
System.out.println(10 * 2058);
prints
20580
where this is 100x the value you need as its fixed precision e.g. cents instead of dollars.
You may want to use double with rounding as below:
double roundingPlaces = 10.0;//use 10.0 for single decimal digit rounding
double a1 = 10.0;
double b1 = 20.58;
double c1 = 1.0;
System.out.println(Math.round((a1*b1*roundingPlaces)/c1)/roundingPlaces);
This prints 205.8.
float fa1 = (float) 10.0;
float fb1 = (float)20.58;
float fc1 = (float)1.0;
System.out.println(fa1*fb1/fc1);
This also prints 205.8
Use float instead of double
http://ideone.com/L9vwR8
System.out.println((float)((10.0f * 20.58f)/1.0f));
output
205.8

Categories

Resources