jQuery/Javascript splitting string calculation - javascript

I'm creating a product page that requires the price to update when the quantity value is changed. Two form fields are used: .orig_price and #quantity. These values are obviously multiplied together.
I'm trying to split the multiplied value, so that I can print the correct format (27.7043454575 should be 27.70).
My code:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = jQuery(".orig_price").val().substr(1);
var qty = jQuery("#quantity").val();
// calculate price
var sumValue = origprice * qty;
// split price
var splitprice = sumValue.split(".");
var pricepound = splitprice[0];
var pricepenny = splitprice[1].substring(0,2);
// update price
jQuery("#pricediv").html('£' + pricepound + '.' + pricepenny);
jQuery("#pricediv").fadeIn(1500);
});
If I remove the split and use sumValue everything works (but format is wrong). Does split not work on a calculation?

You'll want to use sumValue.toFixed(2)
var sumValue = 27.7043454575;
sumValue.toFixed(2) // 27.70
.split does not exist on numeric types. You would have to use sumValue.toString().split('.'), and either way, this would be more inconvenient than simply sticking to .toFixed

You can use toFixed and parseInt() like so:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = parseInt(jQuery(".orig_price").val().substr(1),10);
var qty = parseInt(jQuery("#quantity").val(),10);
// calculate price
var sumValue = origprice * qty;
// split price
var price = sumValue.toFixed(2);
// update price
jQuery("#pricediv").html('£' + price);
jQuery("#pricediv").fadeIn(1500);
});
toFixed determines the number of points after a decimal, and parseInt type-casts the input to an integer (the 10 is unnecessary but there to show it's decimal base 10), because when getting data from a form field it sometimes comes back as a string and messes up your math.

Related

Get subtotal, apply discount, and show new amount

I have the code below but I'm having issues when the dollar amount has commas, for example $1,234.56. When I use the code below, it spits out 0.00. It should show the new subtotal with comma(s) if it's over a thousand.
var subtotal = $('.divWithAmount').text().replace("$",""); // Get the subtotal amount and remove the dollar sign
var discount = subtotal * 0.2; // Multiply the amount by 20%
var newSub = subtotal - discount; // Calculate the new subtotal
var newSubtotal = newSub.toFixed(2); // Show only the last two numbers after the decimal
console.log(newSubtotal);
Thanks for your help!
The main reason it doesn't work is that the returned value from $('.divWithAmount').text() is of type String
To do operations it needs to be a number, and to enable that you also need to remove the comma and then parse it with e.g. parseFloat().
var subtotal = parseFloat($('div').text().replace("$","").replace(",",""));
var discount = subtotal * 0.2; // Multiply the amount by 20%
var newSub = subtotal - discount; // Calculate the new subtotal
var newSubtotal = newSub.toFixed(2); // Show only the last two numbers after the decimal
console.log(parseFloat(newSubtotal).toLocaleString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>$51,234.56</div>
As commented, I updated my answer with toLocaleString, so the comma gets added back.
Here is a couple of ways how to localize the end result:
- Javascript Thousand Separator / string format
- Add thousands separator to auto sum
- convert a JavaScript string variable to decimal/money
to get number out of string value just do like this
var amount = "$1,234.56";
var doublenumber = Number(amount.replace(/[^0-9\.]+/g,""));
once you get number then you can perform operation you want and it will resolve your issue that you are facing.

How to calculate with numbers in jquery?

I am wanting to subtract some values of inputs with the total price.
The code:
$('.calculate-resterend').click(function(e) {
e.preventDefault();
var contant = $('.checkout-contant').val();
var pin = $('.checkout-pin').val();
var creditcard = $('.checkout-creditcard').val();
var waardebon = $('.checkout-waardebon').val();
var totalprice = $('.total.final-price.price').text();
alert(contant - totalprice);
});
But this returns NaN. I figure it's because total price is .text();,
but what is the correct way to substract between these things.
Lets say var contant has a value of 2000,98
and the total price has a value of 2400,99
I want it to return 400,01.
Use Number()
alert(Number(contant) - Number(totalprice));
If you also want to remove comman(,)
alert(Number(contant.replace(/\,/g,'')) - Number(totalprice.replace(/\,/g,'')));
You may have to convert one of your values using parseInt. You can try the following:
totalprice = parseInt(totalprice)
And then proceed to do your simple subtraction like before. You could also try to make your own price attribute on the HTML element itself and the fetch the attribute value instead like .attr("price"). Not sure if that would return a string as well.
try to convert your value by using parseint()
eg:- parseint(your_value)

Adding percentage to a price field incl. currency code

I'm trying to add 10% to a price field via javascript and so far i haven't been able to, and was hoping you guys would be able to help.
The field incl. currency code etc.
I did try something in this direction:
<script type="text/javascript">
$( document ).ready(function() {
var Total = $("#cashamount");
Total.val(Total.val() * 1.1);
});
</script>
But that didn't work ;(
The price field shows up like the following.
<span id="cashamount" class="additional xxlarge carrental_total_amount">48,300.00 ISK</span>
After adding the 10% to the price, it should say in this example:
<span id="cashamount" class="additional xxlarge carrental_total_amount">53,130.00 ISK</span>
Any ideas are welcome, and i would really appreciate help on this matter as i do think it's fairly simple but i'm not very well into Javascripting.
First this: (solution below)
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the
.val() method returns an array containing each selected option; if no
option is selected, it returns null, jQuery docs
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method,
jQuery docs
So, one solution would be next:
var Total = $("#cashamount");
var totalNumber = Number(Total.text().replace(/[^0-9\.]+/g,""));
Total.text((totalNumber * 1.1).toFixed(2));
//Add currency to this
Here's JsFiddle
var x = $("#cashamount").html(); // Fetching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
$("#cashamount").html(y); // Setting the html;
So you can create a function for this:
function updateVal(elem){
var x = elem.html(); // Fethching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
elem.html(y); // Setting the html;
}
and use it as:
$(document).ready(function(){
updateVal($("#cashamount"))
});

How to stop JavaScript removing the 0 from a number after the decimal point?

I am using JQuery to do some calculations on some items that a user selects. One of the items which is priced at £13.95, when 2 are selected gives £27.90. However, the result is always displayed as £27.9, the sum removes the last 0.
How can I stop the Javascript doing this? Here is the code I am using - #pucMoH contains 13.95 as a string, which is then converted to a float:
var MoHCost = parseFloat($('#pucMoH').text()).toFixed(2);
var SelectedVal = parseFloat($(this).val()).toFixed(2);
var SelectedSum = MoHCost * SelectedValInt;
The answer is in your question; toFixed(2):
var MoHCost = parseFloat($('#pucMoH').text()).toFixed(2);
var SelectedVal = parseFloat($(this).val()).toFixed(2);
var SelectedSum = (MoHCost * SelectedValInt).toFixed(2);

Javascript .val() issue

When I enter a decimal for chance, it returns NaN for pay and profit. Any idea why? Also what would I need to do to round profit to the second decimal.
Thanks.
$(document).ready(function(){
function updateValues() {
// Grab all the value just incase they're needed.
var chance = $('#chance').val();
var bet = $('#bet').val();
var pay = $('#pay').val();
var profit = $('#profit').val();
// Calculate the new payout.
var remainder = 101 - chance;
pay = Math.floor((992/(chance+0.5)) *100)/100;
// Calculate the new profit.
profit = bet*pay-bet;
// Set the new input values.
$('#chance').val(chance);
$('#bet').val(bet);
$('#pay').val(pay);
$('#profit').val(profit);
}
$('#chance').keyup(updateValues);
$('#bet').keyup(updateValues);
$('#pay').keyup(updateValues);
$('#profit').keyup(updateValues);
});
First make use of parseFloat or (parseInt if you don't need float values).
function updateValues() {
var chance = parseFloat($('#chance').val());
var bet = parseFloat($('#bet').val());
var pay = parseFloat($('#pay').val());
var profit = parseFloat($('#profit').val());
// Calculate the new payout.
var remainder = 101 - chance;
pay = Math.floor((992/(chance+0.5)) *100)/100;
}
Also what would I need to do to round profit to the second decimal.
you can do this:
profit = bet*pay-bet;
profit = profit.toFixed(2);
You need to use parseFloat to properly work with the values, which by default are strings:
var chance = parseFloat($('#pay').val());
/*same for other values*/
To round the profit to 2 decimals, you can use toFixed on that number, which again converts it back to a string.
3.123.toFixed(2) = "3.12"
Try using parseFloat:
var chance = parseFloat($("#Chance").val());
You can also use toFixed to specify the number of decimal places.
Edit
You need to modify chance:
chance = parseFloat(chance);
You can see this working here:
http://jsfiddle.net/U8bpX/

Categories

Resources