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
Related
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);
I have a flot graphs with a custom tick formatter function,
if ((val / 1000) >= 1) {
val = String(Math.round(val / 1000)) + 'K';
}
return String(val);
But the issue is it returns same values for some ticks.
Little explanation about code:
val --> any integer value ranging from 1 to infinity
val / 1000 logic is to convert the tick into user friends (readable) format (1K, 2K etc).
But the issue here is I get repeated tick labels when some val round up to equal values.
It want to know any good way to fix this algorithm to calculate this?
Addendum
val / 1000 does not mean val is multiple of 1000 it could be any integer value ranging from 1 to infinity.
Eg: For val = 1000 or 1001 it return 1K on two tick labels.
I know its algorithmic bug .I just wanna to know if there is any way to fix it cleanly
Notes
Ticks must be rounding to two decimal at the most (great if no decimal points).
You cannot change val / 1000. You can Play round with Math.round() function.
Even if want to use toFixed() follow Rule 1
Here's a solution that uses suffixes for large numbers while keeping the accuracy:
function tick_label(val) {
if (val < 0) return "\u2212" + tick_label(-val);
if (val < 1000) return String(val);
var mag = 1;
var suffix = "";
if (val >= 1000) { mag = 1000; suffix = "k" }
if (val >= 1000000) { mag = 1000000; suffix = "M" }
if (val >= 1000000000) { mag = 1000000000; suffix = "G" }
var div = mag;
while (val % 10 == 0) {
val /= 10;
div /= 10;
}
return String(val / div) + suffix;
}
This code relies on round numbers for ticks, so that the exact number doesn't look strange or overly exact. (A scale of 1.002k, 1.004k, 1.006k looks okay, but a scale of 1.102k, 1.202k, 1.302k does not. I'm not familiar with Flot, but I guess it takes care of that.)
This question already has answers here:
How to round to at most 2 decimal places, if necessary
(91 answers)
Closed 5 years ago.
I have the following JavaScript syntax:
var discount = Math.round(100 - (price / listprice) * 100);
This rounds up to the whole number. How can I return the result with two decimal places?
NOTE - See Edit 4 if 3 digit precision is important
var discount = (price / listprice).toFixed(2);
toFixed will round up or down for you depending on the values beyond 2 decimals.
Example: http://jsfiddle.net/calder12/tv9HY/
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Edit - As mentioned by others this converts the result to a string. To avoid this:
var discount = +((price / listprice).toFixed(2));
Edit 2- As also mentioned in the comments this function fails in some precision, in the case of 1.005 for example it will return 1.00 instead of 1.01. If accuracy to this degree is important I've found this answer: https://stackoverflow.com/a/32605063/1726511 Which seems to work well with all the tests I've tried.
There is one minor modification required though, the function in the answer linked above returns whole numbers when it rounds to one, so for example 99.004 will return 99 instead of 99.00 which isn't ideal for displaying prices.
Edit 3 - Seems having the toFixed on the actual return was STILL screwing up some numbers, this final edit appears to work. Geez so many reworks!
var discount = roundTo((price / listprice), 2);
function roundTo(n, digits) {
if (digits === undefined) {
digits = 0;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
var test =(Math.round(n) / multiplicator);
return +(test.toFixed(digits));
}
See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/
Edit 4 - You guys are killing me. Edit 3 fails on negative numbers, without digging into why it's just easier to deal with turning a negative number positive before doing the rounding, then turning it back before returning the result.
function roundTo(n, digits) {
var negative = false;
if (digits === undefined) {
digits = 0;
}
if (n < 0) {
negative = true;
n = n * -1;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
n = (Math.round(n) / multiplicator).toFixed(digits);
if (negative) {
n = (n * -1).toFixed(digits);
}
return n;
}
Fiddle: https://jsfiddle.net/3Lbhfy5s/79/
If you use a unary plus to convert a string to a number as documented on MDN.
For example:+discount.toFixed(2)
The functions Math.round() and .toFixed() is meant to round to the nearest integer. You'll get incorrect results when dealing with decimals and using the "multiply and divide" method for Math.round() or parameter for .toFixed(). For example, if you try to round 1.005 using Math.round(1.005 * 100) / 100 then you'll get the result of 1, and 1.00 using .toFixed(2) instead of getting the correct answer of 1.01.
You can use following to solve this issue:
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');
Add .toFixed(2) to get the two decimal places you wanted.
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);
You could make a function that will handle the rounding for you:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
Example:
https://jsfiddle.net/k5tpq3pd/36/
Alternative
You can add a round function to Number using prototype. I would not suggest adding .toFixed() here as it would return a string instead of number.
Number.prototype.round = function(decimals) {
return Number((Math.round(this + "e" + decimals) + "e-" + decimals));
}
and use it like this:
var numberToRound = 100 - (price / listprice) * 100;
numberToRound.round(2);
numberToRound.round(2).toFixed(2); //Converts it to string with two decimals
Example
https://jsfiddle.net/k5tpq3pd/35/
Source: http://www.jacklmoore.com/notes/rounding-in-javascript/
To get the result with two decimals, you can do like this :
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.
The best and simple solution I found is
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // 1.01
try using discount.toFixed(2);
I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Or plain javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
A small variation on the accepted answer.
toFixed(2) returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:
var discount = + ((price / listprice).toFixed(2));
Edited:
I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to
var discount = Math.round(price / listprice * 100) / 100;
This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
Fastest Way - faster than toFixed():
TWO DECIMALS
x = .123456
result = Math.round(x * 100) / 100 // result .12
THREE DECIMALS
x = .123456
result = Math.round(x * 1000) / 1000 // result .123
function round(num,dec)
{
num = Math.round(num+'e'+dec)
return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)
Here is a working example
var value=200.2365455;
result=Math.round(value*100)/100 //result will be 200.24
To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.
var testNum = 134.9567654;
var decPl = 2;
var testRes = roundDec(testNum,decPl);
alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);
function roundDec(nbr,dec_places){
var mult = Math.pow(10,dec_places);
return Math.round(nbr * mult) / mult;
}
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) );
I am having trouble with a simple JavaScript calculation. My document is supposed to add $1.50 to an order if it is $25 or less, or add 10% of the order if it is more then $25. The exact problem is:
Many companies normally charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box.
This is my code:
var price = window.prompt("What is the purchase price?", 0);
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else{
return price * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
When testing I enter a number in the prompt box, and instead of calculating as if I entered a number it calculates as if I entered a string. i.e. i enter 19 and it gives me 191.5 or I enter 26 and it gives me 262.6
Using parseFloat will help you:
var price = parseFloat(window.prompt("What is the purchase price?", 0))
var shipping = parseFloat(calculateShipping(price));
var total = price +shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else{
return price * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
See it working at: http://jsfiddle.net/e8U6W/
Also, a little-known put more performant way of doing this would be simply to -0:
var price =window.prompt("What is the purchase price?", 0) - 0;
(See: Is Subtracting Zero some sort of JavaScript performance trick?)
Be sure to comment this, though as its not as obvious to those reading your code as parseFloat
you can easily convert a string to a number
http://www.javascripter.net/faq/convert2.htm
basically JS provides parseInt and parseFloat methods...
Actually, you need to cast your text results into float values using parseFloat()
http://www.w3schools.com/jsref/jsref_parseFloat.asp
See my answer to the s/o question "Javascript adding two numbers incorrectly".
A bit of redundant multiplication, but your problem is that the numbers that are being inputted are treated as strings, not numbers. You have to convert them to floating point numbers:
var price = parseFloat(window.prompt("What is the purchase price?", 0));
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price)
{
if (price <= 25)
{
return 1.5;
} else {
return price / 10
}
}
window.alert("Your total is $" + total + ".");
var price = parseFloat(window.prompt("What is the purchase price?", 0));
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price){
var num = new Number(price);
if (num <= 25){
return 1.5;
} else{
return num * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
This should do it for you.