0

I'm working on a customized calculator, which is working pretty well except that I can't figure out how to get the generated numbers to display commas within the number. For example, it might spit out "450000" when I need it to say "450,000". This thread gives a number of suggestions on how to create a new function to deal with the problem, but I'm rather new to JavaScript and I don't really know how to make such a function interact with what I have now. I'd really appreciate any help as to how to get generated numbers with commas! :)

HTML:

    <table id="inputValues">
        <tr>
        <td>Percentage:</td>
        <td><input id="sempPer" type="text"></td>
        </tr>

        <tr>
        <td>Price:</td>
        <td><input id="unitPrice" type="text"></td>
        </tr>

        <tr>
        <td colspan="2"><input id="button" type="submit" value="Calculate"></td>
        </tr>
    </table>

    <table id="revenue" class="TFtable">
    <tr>
    <td class="bold">Market Share</td>
    <td class="bold">Partner A</td>
    <td class="bold">Partner B</td>
    </tr>

    <tr>
    <td class="bold">1%</td>
    <td><span id="moss1"></span></td>
    <td><span id="semp1"></span></td>
    </tr>

    </table>

    </form>

JavaScript:

<script>
    function calc() {
        var z = Number(document.getElementById('sempPer').value);
        var x = Number(document.getElementById('unitPrice').value);
        var y = z / 100;
        var dm1 = .01 * 50000 * x * (1-y);
        var se1 = .01 * 50000 * x * y;


            document.getElementById("moss1").innerHTML= "$"+Number(dm1).toFixed(2);
            document.getElementById("semp1").innerHTML= "$"+Number(se1).toFixed(2);
    }
</script>
Community
  • 1
  • 1
m-use
  • 363
  • 1
  • 4
  • 16
  • This can help with the commas: http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – Alex Aug 22 '14 at 03:47
  • I've tried a hundred different ways to get the commas to display, but nothing has worked, which is why I made a post about it. I know where to look for answers, but do not know how to integrate those answers with my problem. I'm really new to JavaScript and really don't have the knowhow to take an answer for one problem and form it to fit my own. – m-use Aug 22 '14 at 03:49

2 Answers2

0

Try .toLocaleString() instead of .toFixed().

Scott Cramer
  • 304
  • 2
  • 3
0

Improve your number display with this cool library.

https://github.com/HubSpot/humanize

A glance of some useful APIs.

Humanize.formatNumber(123456789, 2)
// "123,456,789.00"

Humanize.intComma(123456789)
// "123,456,789"

Humanize.compactInteger(-7832186132456328967, 4)
// "-7.8322x10^18"

Pretty cool~