1

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

user3707061
  • 33
  • 1
  • 4
  • 3
    You will have to do the formatting yourself, or you can use a [library](http://openexchangerates.github.io/accounting.js/). See [this question](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript). – Spencer Wieczorek Apr 19 '15 at 19:37
  • possible duplicate of [How to format numbers using javascript?](http://stackoverflow.com/questions/5731193/how-to-format-numbers-using-javascript) – Rune FS Apr 19 '15 at 19:37
  • Check this post out, http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript will probably give you some ideas – David Rubin Apr 19 '15 at 19:59

3 Answers3

0

You simply need to divide by 100 to turn the cents you get into dollars, then add commas and the pound sign.

Here is an in-depth answer which covers how to format the number as money: How can I format numbers as money in JavaScript?

Community
  • 1
  • 1
Matt Wetmore
  • 300
  • 2
  • 5
0

The 'most modern' answer is:

(value/100).toLocaleString("en-gb",{style:'currency',currency:'GBP',minimumFractionDigits:2})

However, this will fail in a variety of older browsers (see the documentation).

S McCrohan
  • 6,663
  • 1
  • 30
  • 39
0

Was interested to see what a function to implement currency formatting in browsers that don't support (or units not supported by) number.toLocaleString would look like, came up with this, default currency is GBP

function currency(val, unit, tsep, usep, rounder) {
    var re = /(\d+)(?=(?:\d{3})+)/g,
        arr = [];

    if (typeof val !== 'number' || val !== val || val === Infinity || val === -Infinity)
        throw TypeError('Invalid value: ' + val);

    if (typeof unit !== 'string') unit = '£';
    if (typeof tsep !== 'string') tsep = ',';
    if (typeof usep !== 'string') usep = '.';
    if (typeof rounder !== 'function') rounder = Math.round;

    if (val < 0)
        unit = unit + ' -', val = -val;

    arr[0] = Math.floor(val);
    arr[1] = '' + rounder((val * 100) - (arr[0] * 100));

    arr[0] = ('' + arr[0]).replace(re, '$1' + tsep);

    if (arr[1] === '0') 
        arr[1] = ''; // or `usep + '00'`
    else {
        arr[1] = usep + '00'.slice(arr[1].length) + arr[1];
    }

    return unit + arr[0] + arr[1];
}

Usage example,

currency(220500 / 100); // "£2,205"
currency(-220500 / 100); // "£ -2,205"
Paul S.
  • 64,864
  • 9
  • 122
  • 138