Discordjs adding/subracting money randomly - javascript

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

Related

Ternary Operator not yielding expected result

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);

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

making a function to do multiplication

Hey I'm trying to complete a task it was given at school and I am hitting a wall I have only been learning JavaScript for about 2 days so excuse me if the answer is right in front of my face any and all help is welcome. Below is the instruction given and below the instruction is where I am at with my JavaScript. The problem I am running into is I can't seem to get it to display the cost of the bagels only the amount of bagels themselves I know I am getting close but for the life of me I cannot seem to break through this wall. Thanks in advance and sorry for the blocks of text I am not yet familiar with how to pose questions about these subjects :)
3) calculateBagels
A bagel shop charges 75 cents per bagel for orders of less than a half-dozen bagels and charges 60 cents per bagel for orders of a half-dozen or more bagels. Write a program that requests the number of bagels ordered and displays the total cost.
Test the program for orders of four bagels and a dozen bagels.
function bagelcost(number1){
var result = number1
if(result >= 6){
(result * 0.60)
} else {
(result * 0.75)
}
return result;
}
console.log(bagelcost(100))
You have to store result while multiplication otherwisw it not retain in result variable which you have return
function bagelcost(number1){
var result = number1;
if(result >= 6){
result=result * 0.60;
} else {
result=result * 0.75;
}
return result;
}
console.log(bagelcost(100));
More ever you can directly return result as below
function bagelcost(number1){
if(number1 >= 6){
return number1 * 0.60;
} else {
return number1 * 0.75;
}
}
console.log(bagelcost(200));
You should assign the statements result * 0.60 and result * 0.75 to the result variable
result=result * 0.60;
result=result * 0.75;
You can directly return the calculation. And you can omit the else part, because all code after an if with return is treated as else part. For fixed-point notation use Number.toFixed().
function getBagelCost(count) {
if (count < 6) {
return count * 0.75;
}
return count * 0.6;
}
document.write('$' + getBagelCost(4).toFixed(2) + '<br>');
document.write('$' + getBagelCost(12).toFixed(2) + '<br>');
You were really close.
The key was to save the value. Anything that uses arithmetic like this requires you to capture (assign to a variable, or send as a return value) the result on the left (hence the a = b + c; syntax).
If I might make a suggestion, it might make sense if you use more (and more descriptive) words in your functions.
As you learn (and even as you write software as a day job), it's tempting to use arithmetic everywhere, without much explanation, but it becomes easier to forget what's happening.
The same is true for changing the value multiple times. The more times you save a different value saved at the same name, the less you can tell what's happening when.
function getCostOfBagels (bagelCount) {
var discountPrice = 0.60;
var fullPrice = 0.75;
var discountVolume = 6;
var unitPrice;
if (bagelCount < discountVolume) {
unitPrice = fullPrice;
} else {
unitPrice = discountPrice;
}
var totalCost = bagelCount * unitPrice;
return totalCost;
}
Eventually, you might consider refactoring this kind of code, so that this function only does the calculating:
var discountPrice = 0.60;
var fullPrice = 0.75;
var discountVolume = 6;
function getBagelPrice (unitCount) {
var bagelPrice = (unitCount < discountVolume) ? fullPrice : discountPrice;
return bagelPrice;
}
function getCostOfBagels (bagelCount) {
var unitPrice = getBagelPrice(bagelCount);
var totalCost = bagelCount * unitPrice;
return totalCost;
}
getCostOfBagels(4); // 3.00
getCostOfBagels(12); // 7.20

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