I’ve got everything else working in this contact form invoice but I am not able to make this script to return total money value in the following format: 00.00
I have added the .tofixed(2)
in several places and have only managed to make it return .00 when it should be .60.
I am a self-learner so I am struggling to figure it out.
<script type="text/javascript">
function findTotal(){
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
</script>
3
Answers
There’s 2 method in JavaScript that deals with parsing of number from string:
When dealing with numbers that has decimal points, you would need to use
parseFloat
instead so the decimal part isn’t discarded.How
parseInt()
works is, it will try to match as many valid characters as possible (following theradix
passed in the second argument, usually default to10
except special case*):This is why we need
parseFloat()
to solve the first scenario:(Unlike
parseInt()
, it doesn’t accept aradix
second argument and can only be base of 10)Solution based on your case:
As an option, you can us
totalValue.toLocaleString()
function which will format your target string according to the required currency format.In javascript, the number is not converted to float until it doesn’t have a decimal value greater than 0 even if we use pasrseFloat() on that.
For a decimal number, parseInt() returns us a whole number and on the other hand, parseFloat() provides the results with the decimal value.
For example,
This is where a formatter comes into play i.e. toFixed() which formats the number up to decimal points entered and returns it as a string.
The solution for your code is to change the parseInt to parseFloat while calculating and formatting it with toFixed wherever you need to display it.
}