Get subtotal, apply discount, and show new amount - javascript

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.

Related

Why is my tip calculator multiplying my Total by 10?

I was just trying to make a simple tip calculator that I thought was going to take 5 seconds but something I'm not getting..
Why does this
subTotal = prompt('Total before Tip');
tipPercent = prompt('Percentage to Tip (Please use decimal)');
tip=tipPercent*subTotal;
total = subTotal+tip;
alert('Tip is ' + tip + ' Total is ' + total );
compute total to 10 times what it should be? I checked every other variable and it computes correctly except for subTotal + tip.
total = subTotal+tip;
This concatenates the subTotal string with the tip string.
Cast your values to float first before adding them together.
subTotal = parseFloat(prompt('Total before Tip'));
tipPercent = parseFloat(prompt('Percentage to Tip (Please use decimal)'));
JavaScript is treating subtotal and total as string not floats or integers
conversion will solve your issue like this
Here i am using the Number function to convert any string to the appropriate number type
subTotal = prompt('Total before Tip');
tipPercent = prompt('Percentage to Tip (Please use decimal)');
tip=tipPercent*subTotal;
total = Number(subTotal)+Number(tip);
alert('Tip is ' + tip + ' Total is ' + total );
your prompts are taking in strings and its simply concatenating the strings.
You need to convert the strings to numbers, in the case of your tip calculation js is converting the strings as numbers, but the addition for total its not. try something like this (add the parseInt() before the values to force JS to deal with them as integers):
total = parseInt(subTotal)+parseInt(tip);
Several answers above are correct. The input is STRING but you want to convert them to numbers to do the math on them.
Simplest solution is to convert them as you get the input from the user:
subTotal = Number(prompt('Total before Tip'));
tipPercent = Number(prompt('Percentage to Tip (Please use decimal)'));
Enter 20.00 then .15 will result in 23
The value coming from prompt is not integer. Read up: Window.prompt() - Web APIs | MDN
Convert it using parseInt() - JavaScript | MDN.
Also, you are missing the division by 100 while calculating the tip.
One more thing - if you are not declaring the variables using var, they will be global variables!
Check out this working code snippet:
var subTotal = parseInt(prompt('Total before Tip'));
var tipPercent = parseInt(prompt('Percentage to Tip (Please use decimal)'));
var tip = tipPercent * subTotal/100;
var total = subTotal + tip;
alert('Tip is ' + tip + ' Total is ' + total);

missing zero in cents on one field javascript

there is one form field that is missing the zero in the cents. the form field is total.
the others are ok ( total_t and total_tax work fine ). i have tried a few things but it either stops working or just doesnt add the zero on the end of the calculation.
example being if a product is 0.20 it shows as 0.2 and misses the zero on the end in the total field. but the tax and after tax work fine
<script>
$('document').ready(function(){
$('.input-qty').on('input', function(){
var total = 0;
var qty = $(this).val();
var price_single = $(this).parent().parent().parent().find('.input-price-single').val();
$(this).parent().parent().parent().find('.input-price-total').val(parseFloat(qty * price_single).toFixed(2));
$('.input-price-total').each(function(){
total += Number($(this).val());
});
total_t = Number(parseFloat(total).toFixed(2));
total_tax = parseFloat((total_t * 0.10) + total_t).toFixed(2);
$('.input-total').val(total_t);
$('.input-total-tax').val(total_tax);
});
});
</script>
so i guess it would be this section here:
$(this).parent().parent().parent().find('.input-price-total').val(parseFloat(qty * price_single).toFixed(2));
$('.input-price-total').each(function(){
total += Number($(this).val());
There are a few things 'wrong' with your code. (And it's all in your comment section too).
I'll try to fix them putting the answers together (but the credits really go to the people who suggested it.)
<script>
$('document').ready(function(){
$('.input-qty').on('input', function(){
var total = 0;
var qty = $(this).val();
var parent = $(this).parent().parent().parent();
var price_single = $(parent).find('.input-price-single').val();
$(parent).find('.input-price-total').val((qty * price_single).toFixed(2));
$('.input-price-total').each(function(){
total += Number($(this).val());
});
$('.input-total').val(total.toFixed(2));
$('.input-total-tax').val((total * 1.10).toFixed(2));
});
});
</script>
I don't have the corresponding HTML for this, so I can't try it on a fiddle or anything, so this is solely from the top of my head. (Untested)
Your error rests in the lines:
total_t = Number(parseFloat(total).toFixed(2));
$('.input-total').val(total_t);
In these lines, you assign the result of your total-calculation parsed to a float, parsed to a string and then cast to a number (and that's where the real problem sits).
That means, instead of assigning a string (with the correct amount of digits) to the field, you're assigning a variable of type 'number', which assumes the formatting it deems as 'right'.
Now, if you don't want to take all my corrections (after all they're quite a few and also untested), you might roll with something like:
total_t = Number(parseFloat(total));
$('.input-total').val(total_t.toFixed(2));
This should fix your problem.

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/

jQuery/Javascript splitting string calculation

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.

simple calculation of integer and decimal number in jquery

Trying to multiply 2 values. Quantity is integer and credit price is decimal number. When I run this code nothing happens.
Does anyone know what is the issue?
Thank you.
$(function(){ // bind the recalc function to the quantity fields
$("#oneCreditSum").after('<label></label>Total: Aud <span id=\"total\"></span><br><br>');
$("#quantity").bind('keyup', recalc);
function recalc(){
var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = quantity * creditPrice;
$("#total").text(total);
}});
Use parseFloat on the values, and alert each one individually to test.
A few other (unrelated) improvements:
Use keyup() function:
$("#quantity").keyup(recalc);
Make function anonymous:
$("#quantity").keyup(function(){...});
Use $(this) on #quantity in the function to avoid calling the jQuery selector again
You could also consider condensing this into a single line of code:
$("#total").text(parseFloat($('#quantity').val()) * parseFloat($('#creditPrice').val()));
To zero-pad you might try something toFixed():
var num = 10;
var result = num.toFixed(2); // result will equal 10.00
I got this snippet from the following site
http://www.mredkj.com/javascript/numberFormat.html
Hope this helps.
use
parseFloat
before calculation on both numbers which parses a string argument and returns a floating point number.
var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = parseFloat(quantity) * parseFloat(creditPrice);
If you are interested in whole number only you can use this function instead:
parseInt

Categories

Resources