been banging my head against the wall all day with this. Could anyone provide some advice please?
I'm trying to multiply (rate * pps) * ts, and return the result in a money format. I've almost got it working, but it's not quite right.
When I enter 5.25 as the percentage for rate, 35.00 for pps, and 1200 for ts, the result is 220500; which is the same as when calculated with a calculator, but I need to return it in the format of £2,205.00
The code I have so far is:
The HTML:
<div class="row"><input type="text" name="rate" id="rate" placeholder="Dividend rate (%) e.g. 5.25" /></div>
<div class="row"><input type="text" name="pps" id="pps" placeholder="Par value (£) e.g. 1" /></div>
<div class="row"><input type="text" name="totalshares" id="totalshares" placeholder="Total number of shares e.g. 1000" /></div>
<div class="row"><input type="text" name="marketprice" id="marketprice" placeholder="Market price (£) e.g. 20" /></div>
<div class="row"><input type="button" value="Calculate dividend" onClick="calculateDividend()" /></div>
<div class="row" id="dividendcont" style="display:none"><input type="text" name="dividend" id="dividend" placeholder="Dividend" /></div>
The javascript:
function calculateDividend(){
var rate = document.getElementById('rate').value;
var pps = document.getElementById('pps').value;
var ts = document.getElementById('totalshares').value;
var dividend = (rate * pps) * ts;
document.getElementById('dividendcont').style.display="block";
document.getElementById('dividend').value = dividend;
}
Any help would be greatly appreciated.
UPDATE: Thanks Matt. That put me on the right track. Here's how I done it in the end:
The JS:
function calculateDividend(){
var rate = document.getElementById('rate').value;
var pps = document.getElementById('pps').value;
var ts = document.getElementById('totalshares').value;
var mp = document.getElementById('marketprice').value;
var dividend = (rate * pps) * ts;
var total = number_format(dividend / 100, 2, ".", ",");
document.getElementById('dividendcont').style.display="block";
document.getElementById('dividend').value = "£"+total;
}
function number_format (number, decimals, dec_point, thousands_sep) {
// Strip all characters but numerical ones.
number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function (n, prec) {
var k = Math.pow(10, prec);
return '' + Math.round(n * k) / k;
};
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
Thanks for your help everyone