I am having trouble calculating with commas in my price what would be de best solution to solve this?
I am console log the right price and want to get the tax.
example console log: "€1.652,89"
$(document).ajaxSuccess(function() {
var price = $('.yith_wcp_group_final_total').text();
console.log(price);
var tax = 21
var total = (price * tax) / 100;
$('#B_subtotal').html(total);
console.log(total);
});
//EDIT
$(document).ajaxSuccess(function() {
var price = $('.yith_wcp_group_final_total').text();
price = Number(price.replace(/[^0-9\.-]+/g,""));
console.log(price)
var tax = 21
var total = price * (100 + tax) / 100;
var roundup = total.toFixed(2);
$('#B_subtotal').html(roundup);
console.log(total);
console.log(roundup);
});
So i get 1.900,83
and after the calculation i get 2.3000043
How could I get the comma and dots back on the right place?
You are getting values in a string. Just convert the string into a float as we have a decimal point and apply regex as we have a currency sign in it. Regex will check the value and we will get the value in float which can be used with tax multiplication.
var price = $('.yith_wcp_group_final_total').text();
price = Number(price.replace(/[^0-9\.-]+/g,""));
console.log(price)
var tax = 21
var total = (price * tax) / 100;
$('#B_subtotal').html(total);
total = price + total
console.log(total.toLocaleString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
First you need to convert "€1.652,89" from "currency" to float. In this example I used the parseLocaleNumber function (https://stackoverflow.com/a/29273131/5334486).
This gives you float 1652.89 which can be correctly used to compute taxes and total.
You can then format total back to currency using Intl.NumberFormat() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
let price = "€1.652,89"
const taxPercent = 21
// REMOVE THE EURO SYMBOL FROM PRICE
price = price.substring(1)
// CONVERT LOCALIZED NUMBER TO FLOAT
const priceAsNumber = parseLocaleNumber(price, 'nl')
console.log(priceAsNumber) // 1652.89
// GET TAXES
const taxAmount = priceAsNumber * taxPercent / 100
console.log(taxAmount) // 347.1069
// GET TOTAL
const total = priceAsNumber + taxAmount
console.log(total) // 1999.9969
// FORMAT TOTAL TO CURRENCY
const totalRounded = new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR' }).format(total)
console.log(totalRounded) // "€ 2.000,00"
//
// HELPER FUNCTION
//
// https://stackoverflow.com/a/29273131/5334486
//
function parseLocaleNumber(stringNumber, locale) {
var thousandSeparator = Intl.NumberFormat(locale).format(11111).replace(/\p{Number}/gu, '');
var decimalSeparator = Intl.NumberFormat(locale).format(1.1).replace(/\p{Number}/gu, '');
return parseFloat(stringNumber
.replace(new RegExp('\\' + thousandSeparator, 'g'), '')
.replace(new RegExp('\\' + decimalSeparator), '.')
);
}
Related
I am trying to make my program work, but something is wrong. I want to do a simple tax program, where I am calculating the total price including tax on X amount of items. I want to enter the values using prompt command in JavaScript. Here is my code:
let phonePrice;
let quantity;
let tax;
let total;
let total2;
phonePrice = prompt('Enter the phone price here...','');
quantity = prompt('Enter quantity here...','');
tax = phonePrice * 0.05;
total = phonePrice + tax;
total2 = quantity * total
alert('The Price on ' + quantity + ' phones with tax included is ' + total2 + ' dollars.');
Everything works fine until I want to add decimal number as value. Quantity can't be decimal number of course, but, for example, the item price can be 119.95 dollars. When I enter this number directly in ti the script (without prompt) everything is fine, but when i declare prompt and enter the same value in the browser, it give me NaN as value which is not a number. Anyone got any explanation, and how can I fix this?
Try to debug your code, and you will see that problem not in parsing :)
You have STRING in phonePrice (the result of promt is string, let it be '10.5')
Then you have (tax = phonePrice * 0.05;) Result will be float (autoconverted) = 0.525
Then you have (total = phonePrice + tax;) Result will be STRING = "10.50.525" - because in '+' operator , if any argument STRING - all will be used as STRINGs
And then you got NaN in last '*' - because no one know the number "10.50.525" :) and result of float * NaN = NaN
Just try to convert input values.
let phonePrice;
let quantity;
let tax;
let total;
let total2;
phonePrice = parseFloat(prompt('Enter the phone price here...',''));
quantity = parseFloat(prompt('Enter quantity here...',''));
tax = phonePrice * 0.05;
total = phonePrice + tax;
total2 = (quantity * total).toFixed(2); // Needed for correct result to money conversion
alert('The Price on ' + quantity + ' phones with tax included is ' + total2 + ' dollars.');
You have to convert the input from the prompt, which is parsed as a string, into a number, with parseFloat and parseInt:
let phonePrice;
let quantity;
let tax;
let total;
let total2;
phonePrice = parseFloat(prompt('Enter the phone price here...',''));
quantity = parseInt(prompt('Enter quantity here...',''));
tax = phonePrice * 0.05;
total = phonePrice + tax;
total2 = quantity * total
alert('The Price on ' + quantity + ' phones with tax included is ' + total2 + ' dollars.');
That said, you should instead count your money in cents instead of dollars, and use integers instead of floats, to avoid errors with floating-point accuracy.
FIDDLE
https://jsfiddle.net/o1hq1apw/2/
The current BTC price is 2700$.
The price has increased by +34% in 7Days.
I hold 3.011 BTC, how can i calculate my profit?
currentPrice = 2700;
percent = 34;
holdings = 3.011;
alert( calcPec(currentPrice,percent,holdings) );
The current BTC price is 2700$.
The price has increased by -7% in 2Days.
I hold 3.011 BTC, how can i calculate my loss?
currentPrice = 2700;
percent = -7;
holdings = 3.011;
alert( calcPec(currentPrice,percent,holdings) );
// This is what i have but it is not correct
function calcPec(currentPrice,percent,holdings)
{
res = currentPrice*percent/2;
sum = holdings*res;
return '$'+sum;
}
So you hold 3.011 BTC which is currently 2700$ per BTC.
7 days ago the price of on BTC was equal to 100%, now it has risen by 34% so the 2700$ equal 134%.
To calculate the price from 7 days ago you have to divide 2700 by 134%, which is approx. 2014$.
So your earnings are (2700 - 2014) * 3.011 = 2065
Your code should be the following:
function calcPec(currentPrice, percent, holdings)
{
oldPrice = currentPrice / ((100 + percent) / 100);
sum = (currentPrice - oldPrice) * holdings;
}
You forgot to divide the percentage by 100 to get a fraction.
// The current BTC price is 2700$.
// The price has increased by +34% in 7Days.
// I hold 3.011 BTC, how can i calculate my profit?
currentPrice = 2700;
percent = 34;
holdings = 3.011;
console.log(calcPec(currentPrice, percent, holdings));
// The current BTC price is 2700$.
// The price has increased by -7% in 2Days.
// I hold 3.011 BTC, how can i calculate my loss?
currentPrice = 2700;
percent = -7;
holdings = 3.011;
console.log(calcPec(currentPrice, percent, holdings));
function calcPec(currentPrice, percent, holdings) {
const curr = holdings * currentPrice;
const changed = curr * (1 + (percent / 100));
return '$' + (changed - curr);
}
In future you probably want to define your percentage as a fraction to begin with, to avoid errors like this. So instead of percent = 34 you'd do percent = 0.34
EDIT fixed other errors too;
You could divide the percent value by 100 to the the fraction of the change.
function calcPec(price, percent, holdings) {
return '$' + (holdings * price * percent / 100).toFixed(2);
}
console.log(calcPec(2700, 34, 3.011));
console.log(calcPec(2700, -7, 3.011));
I can't get the var total to resolve by using addition. It will work with multiplication operator:
var total = subtotal * sales_tax
but not with the + sign addition operator: var total = subtotal + sales_tax. Any help would be most appreciated.
var calculate_click = function () {
var subtotal = parseFloat(document.getElementById("subtotal").value).toFixed(3);
var taxRate = parseFloat(document.getElementById("tax_rate").value).toFixed(3);
if (isNaN(subtotal) || isNaN(taxRate)) {
}
else {
var sales_tax = (subtotal * taxRate / 100);
parseFloat(document.getElementById("sales_tax").value = sales_tax.toFixed(3));
var total = subtotal + sales_tax;
parseFloat(document.getElementById("total").value = total.toFixed(3));
}
}
toFixed() formats the number into a string. So arithmetic operations afterwards will not work as expected.
Note:
+ (concatenation) is a valid operation for strings as well, so it'll return "string1string2" - For all other arithmetic operations it auto converts the strings to numbers and performs the operation. If the data within the strings cannot be converted, it returns NaN.
"12" + "2" => "122" whereas "12" * "2" => 24 (number) and "hello" * "3" => NaN
I just want to segment this text file into lines and to classify the lines. If the line starts with "Qty" then the next lines are the order items until the line starts with "GST".
If the line starts with "Total Amount" Then this is the total amount line.
Business me . ' l
Address "rwqagePnnter Pro DemcRafifilp
Address "mfgr Eva|uat|on Only
Contact line 1
Transaction Number 10006
Issue Date 27/02/201
Time 10:36:55
Salesperson orsa orsa
Qty Description Unit Price Total
1 test $120.00 $120.00
GST $10.91
Total Amount $120.00
Cash $120.00
Please contact us for more information about
this receipt.
Thank you for your business.
d
.
test
Please show me how to do with PegJS http://pegjs.majda.cz/
Here's a quick and dirty sample solution
{
var in_quantity = false // Track whether or not we are in a quantity block
var quantity = []
var gst = null
var total = null
}
start =
// look for a quantity, then GST, then a total and finally anything else
(quantity / gst / total / line)+
{
return {quantity: quantity, gst: gst, total: total}
}
chr = [^\n]
eol = "\n"?
quantity = "Qty" chr+ eol { in_quantity = true; }
gst = "GST" g:chr+ eol { in_quantity = false; gst = g.join('').trim(); }
total = "Total Amount" t:line { in_quantity = false; total = t.trim(); }
line =
a:chr+ eol
{
if( in_quantity ){
// break quantities into columns based on tabs
quantity.push( a.join('').split(/[\t]/) );
}
return a.join('');
}
How about the following code as another solution.
{
var result = [];
}
start
= (!QTY AnyLine /
set:(Quantities TotalAmount)
{result.push({orders:set[0], total:set[1]})}
)+ (Chr+)?
{return result;}
QTY = "Qty"
GST = "GST"
Quantities
= QtyLine order:(OrderLine*) GSTLine {return order;}
QtyLine
= QTY Chr* _
OrderLine
= !GST ch:(Chr+) _ {return ch.join('');}
GSTLine
= GST Chr* _
TotalAmount
= "Total Amount" total:(Chr*) _ {return total.join('');}
AnyLine
= ch:(Chr*) _ {return ch.join('');}
Chr
= [^\n]
_
= "\n"
You could use XML, or you could do every line ending with a "/" and then splitting it by them using the split function.
mytext = mytext.split("/");
And then work with that. I don't know why you wouldn't just use sql or something similar.
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) );