missing zero in cents on one field javascript - 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.

Related

Javascript Number formating winthout numbers after comma

I am trying this script to calculate and print the result in a form input readonly. While this works fine i need the numbers to be shown like this: 2.000.000 instead of 2.000.000.00. I need those 2 zeros at the end gone. I googled it but all I find are solutions with the comma intact. As this script is very basic and simple i hope that for my problem there is a very simple and basic solution.
<script>
getPrice = function() {
var numVal1 = Number(document.getElementById("price").value);
var numVal2 = Number(document.getElementById("discount").value) ;
var totalValue = numVal1 * numVal2
document.getElementById("total").value = totalValue.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&.');
}
</script>
Have you tried this :
totalValue.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&.').slice(0, -3)

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);

jquery: percentage of two numbers (Part 2)

this is continuation of last successful topic
jquery: percentage of two numbers
First of all I want to thank you for your prompt support of previuous post.
Now I would like to make my script a little bit more complicated. I want to achive the following: If I insert PRICE1 and PRICE2 to have RATE between THEM, then I can change the RATE with other value and PRICE2 to change to the corespondent value according to RATE value.
My script of calculation is close to be correct, but my low knowledge about JQuery make me to ask you where I do something wrong.
Thank you for your support!
<script src="libs/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#PRICE1, #PRICE2").change(function() {
var result = parseFloat(parseFloat($("#PRICE1").val(), 10) - parseFloat($("#PRICE1").val(), 10))/ parseFloat($("#PRICE2").val(), 10) * 100;
$('#RATE').val(result||'');
})
else {
$("#PRICE1, #RATE").change(function() {
var result = parseFloat(parseFloat($("#PRICE1").val(), 10) * parseFloat($("#RATE").val(), 10))/ 100 + parseFloat($("#PRICE1").val(), 10);
$('#PRICE2').val(result||'');
})}
});
</script>
EDITED:
THE CODE ALMOST WORKING CORRECTLY WHICH MIGHT HELP OTHERS:
$(document).ready(function(){
$("#priceOne, #priceTwo").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var priceTwo = parseFloat($("#priceTwo").val());
$('#Rate').val((priceTwo - priceOne) / priceOne * 100); // Set the rate
});
// If price one or the rate is changed, adjust price two.
$("#priceOne, #RATE").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var rate = parseFloat($("#Rate").val());
$('#priceTwo').val((priceOne * rate)/ 100 + priceOne);
});
})
Thank you everyone who help me!!!
There is a else and no matching if. I'm not sure what you're trying to achieve, but some condition needs to be checked.
I'm going to try and code what it appears you need. But I'm going to rename your variables, not only because allcaps are hard to type, but unless it's a constant or a macro, they shouldn't be used.
// In ready() callback
// #NOTE - This does NO error checking for division by 0 or other NaN operations.
// If price two is changed, adjust the rate.
$("#priceTwo").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var priceTwo = parseFloat($(this).val());
$("#rate").val(priceTwo / priceOne); // Set the rate
});
// If price one or the rate is changed, adjust price two.
$("#rate #priceOne").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var rate = parseFloat($("#rate").val());
$("#priceTwo").val(priceOne * rate);
});
There are a few things about your code that needs attention:
parseFloat doesn't take a radix argument, the 10 you pass it is ignored.
parseFloat(parseFloat(... is pointless, I'm not sure why you've done this.
Don't use jQuery to select the same element multiple times in the same scope. Save the value and re-use it - save yourself some cycles.
As I mentioned, don't name your variables in all capitals unless they are some sort of constant that should never be changed, it's good to have clean style habits.

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