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)
Related
I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1) + parseFloat(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result.toFixed(2));
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
You need to remove the commas before parsing:
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
similiar question on this link
Remove commas from the string using JavaScript
That is because parseFloat() converts the string "1,555.00" to the number 1.
To convert it to a proper floating point number, it needs to include a single dot only.
console.log(parseFloat("1.555"));
how to get output?
there is some problem in the code that is i am not able to get out answer.
and i can't figure that is my mistake
<!Doctypehtml>
<html>
<title>new html</title>
<head>
</head>
<body>
<script >
var number = document.getElementById("num1");
var number2 = document.getElementById("num2");
var out = document.getElementById("output");
number.addEventListener("input", sol);
number2.addEventListener("input", sol);
function sol(){
var one = parseint(number.value);
var two = parseint(number2.value);
out.innerHTML = one+two;
}
</script>
<input id="num1">+<input id="num2">
<p id="output"></p>
</body>
</html>
The function is parseInt (with a capital I) not parseint as mentioned Correctly by #Dai
var one = parseInt(number.value);
var two = parseInt(number2.value);
Here is the Fiddle
And also reason to use textcontext over the innerHTML
innerHTML parses content as HTML and takes longer.
textContent uses straight text, does not parse HTML, and is faster.
Using isNaN() function determines whether a value is an illegal number (Not-a-Number).
if (!isNaN(three))
{
//if its a valid number try to display the value to the output
}
Change parseint to parseInt:
$(document).ready(function () {
var number = document.getElementById("num1");
var number2 = document.getElementById("num2");
var out = document.getElementById("output");
number.addEventListener("input", sol);
number2.addEventListener("input", sol);
function sol() {
var one = parseInt(number.value);
var two = parseInt(number2.value);
out.innerHTML = one + two;
}
});
Demo
Hey first Of all try embedding the java script file into you code except writing an inline JS code because if the code is large then you may get stuck up in assigning events to ID by dertermining the ID values in the HTML.
Secondly, yes you have errors in the following code
function sol(){
var one = parseint(number.value);
var two = parseint(number2.value);
out.innerHTML = one+two;
}
/*the following lines need to be changed /
/ parseInt*/
var one = parseInt(number.value);
var two = parseInt(number2.value);
Thankyou !!
I guess this is what exactly you looking for:
Working : Demo
var number = document.getElementById("num1");
var number2 = document.getElementById("num2");
var out = document.getElementById("output");
function sol(){
var one = parseInt(number.value);
var two = parseInt(number2.value);
if(number2.value != '')
{out.innerHTML = one+two;}
else
{out.innerHTML = '';}
}
<input id="num1">+<input id="num2" onkeyup="sol()">
<p id="output"></p>
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.
How do you format a number to show 2 decimals in JavaScript?
Something along the lines of:
format(x,"9,999.99");
You should use this :
x.toFixed(2);
or if you want to be sure it will work :
parseFloat(x).toFixed(2);
var num = 3.14159;
var fixed = num.toFixed(2);
If you want the commas depending on the locale:
var localed = num.toLocaleString();
Combining both crudely:
var num = 3.14159;
var fixed = num.toFixed(2);
var fixednum = parseFloat(fixed);
var localedFixed = fixednum.toLocaleString();
Use .toFixed(2):
http://www.devguru.com/technologies/javascript/17443.asp
Note this will round your number:
var i = 23.778899;
alert(i.toFixed(2));
gives you
23.78
I'm not sure if you are trying to do this to input or just for displaying text on the page. You can use the masked input plugin for jQuery if you are trying to format input.
http://digitalbush.com/projects/masked-input-plugin/
I'm not so good with JS and for some reason when I try to add two fields together it joins them rather than adding the sum together.. this is the code I'm trying to use..
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = postageVal.substr(1); //68.50
var subtotal = subtotalVal.substr(1); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};
The totalVal is echoing/alerting out 68.50378.00 rather than adding them together.. could someone please tell me where I've gone wrong? :( The idea is to update the "total" textfield with totalVal, but I haven't gotten that far yet!
You need to convert your values to a float before adding them:
var totalVal = parseFloat(postage) + parseFloat(subtotal);
EDIT: Here's a complete example that includes a check for NaN:
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat(postageVal.substr(1)); //68.50
var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
var postageAsFloat = isNaN(postage) ? 0.0 : postage;
var subtotalAsFloat = isNaN(subtotal) ? 0.0 : subtotal;
var totalVal = postageAsFloat + subtotalAsFloat;
alert(postage);
alert(subtotal);
alert(totalVal);
};
Try converting the numbers to floats:
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat(postageVal.substr(1)); //68.50
var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};
Everyone else has the right idea with parseFloat.
I just wanted to mention that I prefer to clean up numeric values like this (as opposed to parsing with substr):
var postageVal = document.getElementById('postage').value; //$68.50
var postage = parseFloat(postageVal.replace(/[^0-9.]/g, ''));
That replace call will remove any characters from the string except 0-9 and . (period). Not the /g at the end of the regex. That's important because, without it, only the first matching occurrence will be replaced.
parseFloat does the trick.
var postage = parseFloat(postageVal.substr(1));
var subtotal = parseFloat(subtotalVal.substr(1));
It's treating postage and subtotal as strings and concatenating them. You could try something like this:
var totalVal = 0+postage+subtotal;
That should force it into number mode.
However this could lead to problems if the values do not end up being numbers. You should run it through the proper number parsing functions and add checks to make sure they parsed correctly or else you will end up with NaN.
You need to parse the number first. This should work.
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat( postageVal.substr(1) ); //68.50
var subtotal = parseFloat( subtotalVal.substr(1) ); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};
Unary plus should work:
var totalVal = (+postage) + (+subtotal);
But you probably intended your postage and subtotal variables to be numbers rather than strings, so...
var postage = +postageVal.substr(1); //68.50
var subtotal = +subtotalVal.substr(1); //378.00
var totalVal = postage+subtotal;
I haven't tested your code so there may be other issues but the fix below using parseFloat should stop the concatenation and add the numbers together.
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = postageVal.substr(1); //68.50
var subtotal = subtotalVal.substr(1); //378.00
var totalVal = parseFloat(postage)+parseFloat(subtotal);
alert(postage);
alert(subtotal);
alert(totalVal);
};
Having had the same sort of trouble I examined the JS parseFloat and parseInt functions and found them to be badly developed.
So therefore I prevent the whole problem by multiplying the element's value's * 1 before adding them. This forces JS to treat the result as numeric even if the value's were empty, so that it can be properly handled. As follows:
var TEMP = (1 * el_1.value) + (1 * el_2.value);
document.getElementById("el_tot").value = TEMP;
Assuming you see that "el_1" et al are the fieldnames in the form.
Thanks for all the answers! I'll try them out, I'm sure they're better than my solution:
<script type="text/javascript">
function calculateTotal() {
var postageVal = document.cart.postage.value;
var subtotalVal = document.cart.subtotal.value;
var postage = postageVal.substr(1);
var subtotal = subtotalVal.substr(1);
var totalVal = Number(postage)+Number(subtotal);
document.cart.total.value = "$"+totalVal.toFixed(2);
};
</script>
1.simple javascript addition program
<!DOCTYPE html>
<html>
<body>
<p>This calculation perfoms an addition, and returns the result by using a JavaScript. Check for a demo</p>
<form>
Enter no 1:<input type="text" name="a"><br>
Enter no 2:<input type="text" name="b"><br>
& nbsp;
<button onclick="calc(this.form)">Calculate</button>
</form>
<script>
function calc(form)
{
var a=eval(form.a.value);
var b=eval(form.b.value);
var c=a+b;
alert("The sum is " + c);
}
</script>
</body>
</html>