Lets say you have website that keeps balance for each user. You give each user option to deposit money into their balance from PayPal, Amazon FPS, Authorize.NET eCheck and Credit Card and maybe couple of there once.
Each of the above companies charges fee. And since you are the receiver you are responsible for fees (except for Adaptive PayPal API there you can say who will pay the fees).
So lets say website user (sender) will deposit you $1000.00
And lets picker fee of 2.9% plus $0.30 fix fee = -$29.30
So the receiver (the website owner) ends up with $970.70
If you try to charge $1029.30 you end up with $999.1503
If you try to charge $1031.11 you end up with $1000.90781 which is acceptable (this is when the fee is increased by 0.181% to 3.081% + 0.30)
So this question is, what is the best way to calculate the 0.181% in Java method
I know this is more of math problem than Java problem but what would be the best algorithm to use for guessing the best fee percentage so the final value would get as close as possible to the final value of what the website user is try to deposit.
So the method should take the actual fee 2.9% (0.029 for multiplication), the fix fee 0.30 the amount the user is trying to deposit and figure out the final sum to be charged that would be as close as possible to the deposit amount.
The way I have been doing it is trying to increase the 2.9% until I hit slightly higher after the fees are subtracted.
UPDATE
As per bellow answers I coded up this method. Any further suggestions are more than welcome:
public static float includeFees(float percentageFee, float fixedFee, float amount) {
BigDecimal amountBD = new BigDecimal(amount);
BigDecimal percentageFeeBD = new BigDecimal(1-percentageFee);
BigDecimal fixedFeeBD = new BigDecimal(fixedFee);
return amountBD.add(fixedFeeBD).divide(percentageFeeBD, 10, BigDecimal.ROUND_UP)
.setScale(2, BigDecimal.ROUND_UP).floatValue();
}
Any time you're dealing with money you'll want to use a precision data type rather than floating point math. In general there are rules about how you round on matters when dealing with things like sales tax.
BigDecimal has parameters you can set to control the rounding behavior that will probably get you to where you need to go. In any case like this the math will never be exact on fractions of a cent but you should be able to guarantee that you'd never charge more than an extra fraction of a penny.
amt_you_receive = amt_customer_pays - .029 * amt_customer_pays - .30
amt_you_receive + .30 = amt_customer_pays * (1 - .029)
(amt_you_receive + .30) / .971 = amt_customer_pays
So take the amount you want to get, add 30 cents, and divide by .971 (aka multiply by approximately 1.029866) to get the amount you should charge.
Related
I got the project assignment in one of the courses and I was confused to finish it. Can you help me to complete this program ?
This is the Study Case.
Make a program to rent hotel room bookings!
Terms:
-Types of Rooms (President Suite, VVIP, Deluxe, Superior)
-Room rates (IDR 1,500,000, - IDR 1,000,000 IDR 800,000 IDR 500,000)
-If staying more than 3 nights, there is a 15% discount
-If the member there is an additional discount of 10%
Input:
-No KTP
-Name
-E-mail
-Gender
-Address
-Phone number
-Type of room
-Length of stay
Output:
-No KTP
-Name
-E-mail
-Gender
-Address
-Phone number
-Type of room
-Room price
-Length of stay
-Discount
-Total pay
I would throw in something here; maybe you can work on top of that. Apparently, the only output values you need to work on are:
Room Price
Discount
Total Pay
That shall simplify the problem a lot. Next up, how to determine Room Price? It seems that flat Room Price is dependent on type of room. Since each type of room has its specific price tag, maybe some data structure in Java can help with that.
Next up, Discount seems to be determined by length of stay. You already have length of stay as input, so figuring out Discount should be straightforward.
Finally, Total Pay seems to be determined by Room Price and Discount. At this point, you shall already have Room Price and length-of-stay discount available. Don’t forget there is also a membership discount, but you have to figure out how to determine membership status.
I have been seeking for an answer but couldn't found it...
I have a bank project and one of the demends are:
"platinum client can have unlimited credit limit".
In the DataBase i've written the value of platinumClientCommisionRate as varchar "unlimited"
But when i need to use it - in java action,
I dont know how to write the method -"get_Platinum_Client_Rate()"
so.. How to write an unlimited number in java as a double or at list as a decimal value
somefriends told me to write '-1' but then how do i proceed with math calculation.
Thank you all
If there is no limit on Platinum Clients, why don't you just skip it in the calculation? Another thing is that if you ever deal with money use BigDecimals.
If you do not know if Integer or Double are big enough for your numbers, use BigDecimal, which is (well theoretically not, but practically) unlimited regarding the range of numbers it can represent.
I can't see why you would want a method like
getPlatinumClientRate()
if you already know it is unlimited?
Better approach IMHO:
Decimal limit = getClientRate(clientId);
if (limit == null) {
// must be Platinum client, he has no limit
}
else {
// ordinary client, tell them to go away or pay extraordinary interest rates.
}
I need some help with my homework assignement. My assignment is to create a program that creates a Till object, takes a payment, issues exact change, tells me which coins I need to use and then tells me how much is in the till after. Below is the code I have written. The USmoney class is done and is working. The teacher offered a cheat sheet. However it's the main class (CoinCalc), getting the till to take the payment and subtract the payment from the amount paid to give me the change that I'm having issues with. Any help would be most appreciated.
public class USmoney {
int dollars = 0;
int cents = 0;
public USmoney(int newcents) {
dollars = newcents /100;
cents = newcents %100;
}
public USmoney(int dollars, int cents) {
this.dollars = dollars;
this.cents = cents;
}
public int getDollars() {
return dollars;
}
public int getCents(){
return cents;
}
}
public class CoinCalc {
public static void main(String[] args) {
USmoney Till1 = new USmoney(100,0);
USmoney billTotal = new USmoney(49);
USmoney amountPaid = new USmoney(100);
double penny = 1;
double nickel = 5;
double dime = 10;
double quarter = 25;
double[] Coin = new double []{penny,nickel,dime,quarter};
}
private void changeFor(USmoney billTotal, USmoney amountPaid) {
}
}
This is a varient of the knapsack problem, you have a couple of steps to implement
Calculate total change
Satisfy change using smallest number of coins
I'd start by implementing a method with the first signature in your USMoney class, and then read up on the knapsack problem in order to implement the second method.
public USMoney subtract(final USMoney value);
public double[] getCoins(final USMoney value);
There are two issues here, which you can consider separately.
Are you able to describe algorithmically how to determine the answer to your question?
Given this description, can you turn it into Java code?
I'll start by addressing the first item: It is essential that you understand exactly what the input is and what the required output is and that you are able to give a precise pseudo code description of how to solve the problem. If you don't know what pseudocode is, then look it up on Wikipedia. Then you can start thinking about how to code it in Java.
From an algorithmic perspective, your problem is very simple.
Say the customer pays amount X and for an item that costs amount C.
First you must check that X >= C. otherwise the customer won't have paid enough, and you can stop right there.
Assuming that X >= C, and that you are able to give exact change, the amount of money in the till will have increased by C after the transaction completes, as this exactly what the customer ends up paying.
Now, the amount of change you have to give should equal X-C. Call this Y.
Test how many times the biggest coin you have available divides Y:
Say the biggest coin has value V, then you should give back the customer Y/V coins of this value.
Afterwards, you need to pay back the customer the remaining money Y'=Y-(Y/V)*V. Make sure you know how division works in Java (see link at the end of this post).
Repeat the procedure to pay Y' back using the second biggest coin and so on.
2.
I won't write out the whole thing in Java, but there are some things you should consider.
Does the Till contain "money" without it being specified exactly what bills/coins it contains, or should you be representing the money as a number of bills and coins?
You will be doing integer division, so your coin values should not be doubles but ints.
You need to access the coin values (how much a dime is worth etc.) from inside the function that calculates change, so the values of the different coins should probably be declared as static member variables of the class CoinCalc, not inside a function.
You need to make sure you know how basic if-else statements and while loops work and how to assign to variables. Then you should be able to code the solution.
You also need to decide what exactly the solution is. It could be a list of coin names with a name repeated for each time it is needed, e.g. [dime,penny,penny], or maybe an array of four numbers with that say how many quartes, dimes, nickels and pennies are needed. If you want a list, you should learn how list datastructures work in Java, by reading the entry LinkedList in the Java documentation.
Good luck!
NB: Because I'm a new user, I can't post as many links as I would like. You can find a good description of division in Java by googling java division and selecting the link to mindprod.com.
It looks like you want help with your changeFor algorithm, so here's an outline:
First subtract billTotal from amountPaid. That will get you how much change to make.
Then make some variables to hold how much change you're giving back. For each of quarter, dime, nickel, penny, if changeRemaining is > the value of the coin, add a coin and subtract the value. Do this for each coin in order until that coin's value fails the test, then move on to the next coin.
In order to call the changeFor() method you need a reference to a CoinCalc class. You can do this different ways, one way is to declare a variable of the CoinCalc class in the main() method like so:
CoinCalc cc = new CoinCalc();
cc.changeFor(billTotal, amountPaid);
But there are still problems, the method changeFor() currently does nothing and the way you have declared the till object and coin array they are not accessible in the changeFor() method.
So work on that problem for a bit then get back to us...
EDIT
Here is how I would structure it, billTotal is a float amountPaid is a USMoney object that internaly keeps track of each denomination of money ($1 bill, quarter, dime, nickel and penny). When someone pays they give you differing amounts of those kinds of money. USMoney needs and method that will return the value of the kinds of money it has (sum of dollars, quarters, etc).
till is another instance of USMoney that has an initial value of the different denominations of money.
USMoney has a method called changeFor(float bill, USMoney paid) that returns another instance of USMoney. You would then call it like so:
USMoney change = till.changeFor(bill, amountPaid);
The changeFor() method then has to determine how to make change based on what is in the till and the difference between bill and the value of amountPaid. NOTE if you don't have enough quarters your calculations should be smart enough to use dimes and nickels if it has enough. If you want to really get clever throw an exception if you can't make change.
float per = (num / (float)totbrwdbksint) * 100;
i m getting the value of per as say 29.475342 . i want it to round off upto two decimal places only.like 29.48 .how to achieve this?
You should do this as part of the formatting - the floating point number itself doesn't have any concept of "two decimal places".
For example, you can use a DecimalFormat with a pattern of "#0.00":
import java.text.*;
public class Test
{
public static void main(String[] args)
{
float y = 12.34567f;
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(y));
}
}
As Jon implies, format for display. The most succinct way to do this is probably using the String class.
float f = 70.9999999f;
String toTwoDecPlaces = String.format("%.2f", f);
This will result in the string "71.00"
If you need to control how rounding is done you should check BigDecimal ist has several rounding modes. http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html
You need to be careful here, this answer is not related to java, it relates to all aspects of decimals in many programming languages hence it is generic. The danger lies with rounding numbers, is this, and it has happened in my experience and know that it can be tricky to deal with:
Supposing you are dealing with prices on items, the pricing you get from a retail supplier may be different to the price the computer tells you, sure it is marginally small, but it could add up to big money.
Adding a sales tax on a price can either be positive or negative, it can impact the operating margin of the profit/loss balance sheets...
If you are in this kind of arena of development, then my advice is not to adjust by rounding up/down...it may not show up on small sales of the items, but it could show up elsewhere...an accountant would spot it...Best thing to do is to simply, truncate it,
e.g. 29.475342 -> 29.47 and leave it at that, why?, the .005 can add up to big profit/loss.
In conjunction to what is discussed here...electronic tills and registers use their own variety of handling this scenario, instead of dealing with XX.XXXXXXXXXX (like computers, which has 27/28 decimal places), it deals with XX.XX.
Its something to keep in mind...
Hope this helps,
Best regards,
Tom.
you can use the formatted print method System.out.printf to do the formatted printing if that's what you need
I have a bunch of data coming in (calls to an automated callcenter) about whether or not a person buys a particular product, 1 for buy, 0 for not buy.
I want to use this data to create an estimated probability that a person will buy a particular product, but the problem is that I may need to do it with relatively little historical data about how many people bought/didn't buy that product.
A friend recommended that with Bayesian probability you can "help" your probability estimate by coming up with a "prior probability distribution", essentially this is information about what you expect to see, prior to taking into account the actual data.
So what I'd like to do is create a method that has something like this signature (Java):
double estimateProbability(double[] priorProbabilities, int buyCount, int noBuyCount);
priorProbabilities is an array of probabilities I've seen for previous products, which this method would use to create a prior distribution for this probability. buyCount and noBuyCount are the actual data specific to this product, from which I want to estimate the probability of the user buying, given the data and the prior. This is returned from the method as a double.
I don't need a mathematically perfect solution, just something that will do better than a uniform or flat prior (ie. probability = buyCount / (buyCount+noBuyCount)). Since I'm far more familiar with source code than mathematical notation, I'd appreciate it if people could use code in their explanation.
Here's the Bayesian computation and one example/test:
def estimateProbability(priorProbs, buyCount, noBuyCount):
# first, estimate the prob that the actual buy/nobuy counts would be observed
# given each of the priors (times a constant that's the same in each case and
# not worth the effort of computing;-)`
condProbs = [p**buyCount * (1.0-p)**noBuyCount for p in priorProbs]
# the normalization factor for the above-mentioned neglected constant
# can most easily be computed just once
normalize = 1.0 / sum(condProbs)
# so here's the probability for each of the prior (starting from a uniform
# metaprior)
priorMeta = [normalize * cp for cp in condProbs]
# so the result is the sum of prior probs weighed by prior metaprobs
return sum(pm * pp for pm, pp in zip(priorMeta, priorProbs))
def example(numProspects=4):
# the a priori prob of buying was either 0.3 or 0.7, how does it change
# depending on how 4 prospects bought or didn't?
for bought in range(0, numProspects+1):
result = estimateProbability([0.3, 0.7], bought, numProspects-bought)
print 'b=%d, p=%.2f' % (bought, result)
example()
output is:
b=0, p=0.31
b=1, p=0.36
b=2, p=0.50
b=3, p=0.64
b=4, p=0.69
which agrees with my by-hand computation for this simple case. Note that the probability of buying, by definition, will always be between the lowest and the highest among the set of priori probabilities; if that's not what you want you might want to introduce a little fudge by introducing two "pseudo-products", one that nobody will ever buy (p=0.0), one that anybody will always buy (p=1.0) -- this gives more weight to actual observations, scarce as they may be, and less to statistics about past products. If we do that here, we get:
b=0, p=0.06
b=1, p=0.36
b=2, p=0.50
b=3, p=0.64
b=4, p=0.94
Intermediate levels of fudging (to account for the unlikely but not impossible chance that this new product may be worse than any one ever previously sold, or better than any of them) can easily be envisioned (give lower weight to the artificial 0.0 and 1.0 probabilities, by adding a vector priorWeights to estimateProbability's arguments).
This kind of thing is a substantial part of what I do all day, now that I work developing applications in Business Intelligence, but I just can't get enough of it...!-)
A really simple way of doing this without any difficult math is to increase buyCount and noBuyCount artificially by adding virtual customers that either bought or didn't buy the product. You can tune how much you believe in each particular prior probability in terms of how many virtual customers you think it is worth.
In pseudocode:
def estimateProbability(priorProbs, buyCount, noBuyCount, faithInPrior=None):
if faithInPrior is None: faithInPrior = [10 for x in buyCount]
adjustedBuyCount = [b + p*f for b,p,f in
zip(buyCount, priorProbs, faithInPrior]
adjustedNoBuyCount = [n + (1-p)*f for n,p,f in
zip(noBuyCount, priorProbs, faithInPrior]
return [b/(b+n) for b,n in zip(adjustedBuyCount, adjustedNoBuyCount]
Sounds like what you're trying to do is Association Rule Learning. I don't have time right now to provide you with any code, but I will point you in the direction of WEKA which is a fantastic open source data mining toolkit for Java. You should find plenty of interesting things there that will help you solve your problem.
As I see it, the best you could do is use the uniform distribution, unless you have some clue regarding the distribution. Or are you talking about making a relationship between this products and products previously bought by the same person in the Amazon Fashion "people who buy this product also buy..." ??