-1
<SCRIPT language="JavaScript">
    height = screen.height;
    width = screen.width;
    document.write( width*height + " pixels");
</SCRIPT>

I would like my answer to return with commas separating the numbers rather than one full number.

Casualty
  • 43
  • 1
  • 1
  • 10

2 Answers2

2

Here's a fun way to do it:

function format(num) {
    return ("" + num).split("").reverse().reduce(function(acc, num, i, orig) {
        return  num + (i && !(i % 3) ? "," : "") + acc;
    }, "");
}

format(777782374);

Prints:

"777,782,374"

Or, if you want to support decimals:

function format(num, fix) {
    var p = num.toFixed(fix).split(".");
    return p[0].split("").reduceRight(function(acc, num, i, orig) {
        var pos = orig.length - i - 1
        return  num + (pos && !(pos % 3) ? "," : "") + acc;
    }, "") + (p[1] ? "." + p[1] : "");
}

format(777782374, 4);

Prints:

"777,782,374.0000"
Wayne
  • 59,728
  • 15
  • 131
  • 126
  • How can I apply that to my code? I'm still very new to javascript and I'm having trouble understanding the code. – Casualty Jan 08 '14 at 18:58
  • `format(width * height)` – Wayne Jan 08 '14 at 18:59
  • This doesn't seem to be working. Am I still missing something? – Casualty Jan 08 '14 at 19:04
  • You're not doing anything with the result. You really shouldn't be using `document.write` but just to get it working, do this: `document.write(format(width * height) + " pixels");` – Wayne Jan 08 '14 at 19:07
  • It still seems to be returning nothing. Here's a screenshot of the code: http://i.imgur.com/rck8WKA.jpg – Casualty Jan 08 '14 at 19:12
  • You're missing a paren after `height` – Wayne Jan 08 '14 at 19:13
  • Got it thanks. How would I make it display no decimal places? – Casualty Jan 08 '14 at 19:16
  • I updated the answer a bit. Either use the first function (that accepts no `fix` argument) or use the second version, but do not pass an argument for `fix`. – Wayne Jan 08 '14 at 19:19
  • Well done. Much appreciated! – Casualty Jan 08 '14 at 19:21
0

Than you shouldn't multiply them?

document.write( width + ", " + height + " pixels");

Jonathan
  • 8,771
  • 4
  • 41
  • 78
  • OP is showing the total number of pixels. That's why the multiplication is needed. – cookie monster Jan 08 '14 at 18:54
  • What he said. I'm trying to display the total amount of pixels on your screen as a whole number, but with commas. Ex: 1920 x 1080 = 2073600. But I would like for it to say 2,073,600. – Casualty Jan 08 '14 at 19:01