Ternary Operator not yielding expected result - javascript

In JavaScript: I have a ternary operator being instructed to return a tip percentage of %15 if the bill amount is between $50-300, otherwise being instructed to reuturn a tip percentage of %20. On a bill amount of $275, it is still yielding %20. I have looked at many examples of functioning ternary operators and my code seems to be properly worded and yet the result comes out incorrect every time. In what way am I failing?
const bill_1 = 40;
const bill_2 = 275;
const bill_3 = 430;
let bill;
let tip_percentage = bill >= 50 && bill <= 300 ? 0.15 : 0.2;
bill = bill_1;
console.log(`The first table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
bill = bill_2;
console.log(`The second table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
bill = bill_3;
console.log(`The third table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
This is the result being given:

As #Matt said in the comment, tip_percentage is not a function and must be calculated each time you change the bill amount.
Try this:
const bill_1 = 40;
const bill_2 = 275;
const bill_3 = 430;
function getTip(bill) {
var tip = (bill >= 50 && bill <= 300) ? 0.15 : 0.2;
return tip;
}
alert(`Bill one's tip: ${getTip(bill_1)}`);
alert(`Bill two's tip: ${getTip(bill_2)}`);
alert(`Bill two's tip: ${getTip(bill_3)}`);

tip_percentage is already calculated.
If you want to make different result values depending on the variable, make them in the form of functions.
const bill_1 = 40;
const bill_2 = 275;
const bill_3 = 430;
const tip_percentage = (bill) => (bill >= 50 && bill <= 300 ? 0.15 : 0.2);
const printTipResult = (bill) => {
console.log(`The third table's bill came out to $${bill}.
After the tip of ${tip_percentage(bill)}%
(equalling: $${bill * tip_percentage(bill)}) was added,
the final amount owed is: $${bill * tip_percentage(bill) + bill}`);
};
printTipResult(bill_1);
printTipResult(bill_2);
printTipResult(bill_3);

Related

Discordjs adding/subracting money randomly

I need help with Discordjs. I have an economy system but idk how to remove/add money randomly!
Basically, I want the command to randomly give money, but has a chance it will take away money.
Here is the code I use for money...
let money = Math.floor(Math.random() * 80) + 1;
db.add(`money_${msg.guild.id}_${user.id}`, money)
db.subract(`money_${msg.guild.id}_{user.id}, money)
You can use Math.random for another random number between 0.0 and 1.0 and use it to determine whether to add or subtract
let money = Math.floor(Math.random() * 80) + 1;
let shouldAdd = Math.random() >= 0.5;
let user = `money_${msg.guild.id}_${user.id}`;
if (shouldAdd) {
db.add(user, money);
} else {
db.subtract(user, money);
}
If you want to add 90% and subtract only 10% of the time then you can use shouldAdd = Math.random() >= 0.1; or tweak it however you want

Subtracting VAT from a number in JavaScript

I am beginner in JS and this code
$('.brutto_amount').each(function (index, value) {
let amount = $(this).text().replace(' brutto / rok', '').replace('(', ''); console.log(amount);
if (discountType == 0) {
let newAmount = (amount - discountValue).toFixed(2);
if(newAmount < 0) newAmount = 1;
$(this).html(`${newAmount} brutto / rok `);
} else if (discountType == 1) {
let newAmount = (amount - ((parseInt(amount) * parseInt(discountValue)) / 100)).toFixed(2);
if(newAmount < 0) newAmount = 1;
$(this).html(`${newAmount} brutto / rok `);
}
});
works fine so far.
How can I subtract 23% VAT from the variable newAmount and round it to 2 decimal places?
I solved the problem similar to what Lapskaus mentions in the comments:
The first is a simple math problem, if your newAmount value is a brutto value, calculating the netto, with a vat of 23%, is as simple as newAmount / 123 * 100. Use calculatedNetto.toFixed(2) to round that to 2 numbers. Be aware though, that calculations in JS will have rounding errors due to floating point precision. For further information about the issue and how to circumvent that, read this. newAmount will be a brutto value which will be 123% from which you want to calculate the 100% value. You substract 23% off of 123 which is too much

More efficient way for calculating margin percent given cost price, unit price, and tax information

I am trying to come up with a better way to calculate margin percent when given cost price, unit price (selling price), and tax information.
The below code works; but is is NOT efficient in any way. It just loops through all the margin percents from -100 --> 1000 percent and when the solution is found it stops looking and breaks out of loop.
My goal is to not have a long running loop and instead calculate it directly instead of trial by error. The reason it is so tricky is because of the way taxes are setup. It is NOT just a straight percent. See comments for information on how tax is calculated. (Cumulative tax)
var cost_price = 100;
var unit_price = 133.10;
//Loop over -100 -> 1000 percent at .01 intervals to try to find margin percent...Not very good
for(var k=-100;k<1000;k+=.01)
{
var margin_percent = k;
var marked_up_price_before_tax = cost_price * (1+(margin_percent/100));
//First tax is 10%...This value is dynamic...could be a different percent
var first_tax = (marked_up_price_before_tax*(10/100));
//Second tax is 10% cumulative...This value is dynamic.. Could be a different percent
var second_tax = (marked_up_price_before_tax + first_tax) *10/100);
var margin_price = marked_up_price_before_tax + first_tax + second_tax;
//Make 2 decimals for comparison purposes
margin_price = parseFloat(Math.round(margin_price * 100) / 100).toFixed(2);
if (margin_price == unit_price)
{
//FOUND IT!
margin_percent = parseFloat(k);
break;
}
}
There are two solutions here - one is the algebra that solves the problem you're actually presenting (because estimation isn't required here), and the other is the code for doing the estimating if it WERE required.
Algebra:
If we express the markup rate and both tax rates as 1 + increase%, it makes our math easier. That is, for a markup of 50%, think of that as a multiplier of 1.5; for a tax rate of 10%, think of that as a multiplier of 1.1. Counted that way, your equation is:
unit_price = cost * markup * tax1 * tax2
Because we're multiplying here and they're both percentage increases, the order we apply the tax doesn't actually matter...in fact, the fact that the second tax includes the first tax in its taxable amount makes our math EASIER.
Solving for markup, that comes out to:
markup = unit_price / (cost * tax1 * tax2)
Code:
Now, the code for doing this sort of estimation - which is interesting, even though this problem doesn't require it. This problem has some useful traits:
You can look at a potential answer and not only tell if it's right, but you can tell if it's too high or too low
The values are continuous
The values are proportional to your input, even if the proportion changes
Given those, you can solve this with a recursive binary search through the space of reasonable values, and perform FAR fewer comparisons than a linear search.
I'd do something like this:
var cost_price = 100;
var unit_price = 130;
var tax_rate_1 = 1.1;
var tax_rate_2 = 1.1;
function estimateMarkup(minMarkup, maxMarkup) {
if (maxMarkup - minMarkup < 0.001) return null;
let markup = (minMarkup + maxMarkup) / 2
let markedupPrice = cost_price * markup * tax_rate_1 * tax_rate_2;
if (Math.round(markedupPrice) == Math.round(unit_price))
return markup;
if (Math.round(markedupPrice) > Math.round(unit_price))
return estimateMarkup(minMarkup,markup);
if (Math.round(markedupPrice) < Math.round(unit_price))
return estimateMarkup(markup,maxMarkup);
}
console.log(estimateMarkup(-100,100))

How do I get cart checkout price exact to the penny using Javascript?

How do I get cart checkout price exact to the penny using Javascript?
Right now after taking out all of the trial .rounds etc I was trying.. I am coming up 1.5 cents too high using a high 15 products/prices to test.
for (var i = 0; i < Cookie.products.length; i++) {
boolActive = Cookie.products[i].og_active;
if (boolActive)
{
itemPrice = Cookie.products[i].price;
itemQty = Cookie.products[i].quantity;
itemDiscountPercent = Cookie.products[i].discount_percent;
subtotal = itemPrice * itemQty;
priceDiscount = (subtotal * itemDiscountPercent);
discountAmount += priceDiscount;
}
}
if (!isNaN(discountAmount))
{
var newCartTotal = (cartTotal - priceDiscount);
alert("New Cart Total: " + newCartTotal);
}
var newCartTotal = (cartTotal - pricediscount).toFixed(2)
that will give you the value, but it will be a string. If you need it to stay numeric, use:
var newCartTotal = ((cartTotal - pricediscount * 100) << 0) / 100;
You need to round the discount for each line item: priceDiscount = round_to_hundredth(subtotal * itemDiscountPercent)
Note that this result may not agree with the result you'd get if you add the unrounded results and then round the sum. However, this is the way invoices usually work when calculated by hand (especially since each item can have a different discount percent, so the discount is calculated for each line).
I think you left out a line saying discountAmount += priceDiscount.
modify your code to :
priceDiscount = parseFloat( (subtotal * itemDiscountPercent).toFixed(2) );
and:
newCartTotal = parseFloat( (cartTotal - priceDiscount).toFixed(2) );

javascript: calculate x% of a number

I am wondering how in javascript if i was given a number (say 10000) and then was given a percentage (say 35.8%)
how would I work out how much that is (eg 3580)
var result = (35.8 / 100) * 10000;
(Thank you jball for this change of order of operations. I didn't consider it).
This is what I would do:
// num is your number
// amount is your percentage
function per(num, amount){
return num*amount/100;
}
...
<html goes here>
...
alert(per(10000, 35.8));
Your percentage divided by 100 (to get the percentage between 0 and 1) times by the number
35.8/100*10000
Best thing is to memorize balance equation in natural way.
Amount / Whole = Percentage / 100
usually You have one variable missing, in this case it is Amount
Amount / 10000 = 35.8 / 100
then you have high school math (proportion) to multiple outer from both sides and inner from both sides.
Amount * 100 = 358 000
Amount = 3580
It works the same in all languages and on paper. JavaScript is no exception.
I use two very useful JS functions:
http://blog.bassta.bg/2013/05/rangetopercent-and-percenttorange/
function rangeToPercent(number, min, max){
return ((number - min) / (max - min));
}
and
function percentToRange(percent, min, max) {
return((max - min) * percent + min);
}
If you want to pass the % as part of your function you should use the following alternative:
<script>
function fpercentStr(quantity, percentString)
{
var percent = new Number(percentString.replace("%", ""));
return fpercent(quantity, percent);
}
function fpercent(quantity, percent)
{
return quantity * percent / 100;
}
document.write("test 1: " + fpercent(10000, 35.873))
document.write("test 2: " + fpercentStr(10000, "35.873%"))
</script>
In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:
function calculatePercent(amount, percent) {
const amountDecimals = getNumberOfDecimals(amount);
const percentDecimals = getNumberOfDecimals(percent);
const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`; // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)
return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
}
function getNumberOfDecimals(number) {
const decimals = parseFloat(number).toString().split('.')[1];
if (decimals) {
return decimals.length;
}
return 0;
}
calculatePercent(20.05, 10); // 2.005
As you can see, I:
Count the number of decimals in both the amount and the percent
Convert both amount and percent to integers using exponential notation
Calculate the exponential notation needed to determine the proper end value
Calculate the end value
The usage of exponential notation was inspired by Jack Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.
It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:
function getPerc(num, percent) {
return Number(num) - ((Number(percent) / 100) * Number(num));
}
// Usage: getPerc(10000, 25);
var number = 10000;
var result = .358 * number;
Harder Way (learning purpose) :
var number = 150
var percent= 10
var result = 0
for (var index = 0; index < number; index++) {
const calculate = index / number * 100
if (calculate == percent) result += index
}
return result

Categories