2

I am currently building a basic webpage for work and want to include a price calculator. The issue is the currency is in Ugandan Shillings so the output is in the hundreds of thousands and millions and will display as a block number (example: 98635816). How to insert commas to make the output number easier to read?

P.S. Here is the HTML for the calculator

<form  oninput="y.value=(19657.86*parseInt(b.value)).toFixed(0);
 x.value=(928.29*parseInt(b.value)).toFixed(0);
 z.value=((y.value)-(x.value)).toFixed(0)">
    <input type="number" id="b" value="0">
    <output name="y" for="a b"></output>
    <output name="x" for="a b"></output>
    <output name="z" for="a b"></output>
rtruszk
  • 3,902
  • 13
  • 36
  • 53
Tim White
  • 23
  • 3
  • 3
    possible duplicate of [Add Commas to JavaScript output](http://stackoverflow.com/questions/6392102/add-commas-to-javascript-output) and many others – JJJ Nov 18 '14 at 08:24
  • possible duplicate of [How to print a number with commas as thousands separators in JavaScript](http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Bergi Nov 18 '14 at 08:31

2 Answers2

2

You can use below specific code:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Or javascript's Number.prototype.toLocaleString. (slower than regex)

var n = 163546872.345
console.log(n.toLocaleString()) // "163,546,872.345"

(!) For people who use node.js or want something different in the browser Numeral.js might be interesting.

Avi L
  • 1,558
  • 2
  • 15
  • 33
2

you can try this:

<form  oninput="y.value=numberWithCommas((19657.86*parseInt(b.value)).toFixed(0));
 x.value=numberWithCommas((928.29*parseInt(b.value)).toFixed(0));
 z.value=numberWithCommas(((19657.86*parseInt(b.value))-(928.29*parseInt(b.value))).toFixed(0))">
    <input type="number" id="b" value="0">
    <output name="y" for="a b"></output>
    <output name="x" for="a b"></output>
    <output name="z" for="a b"></output>

    <script>
    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    </script>
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44