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?
2
Answers
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.
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 usingIntl.NumberFormat()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat