0

I have a number which currently is 1,657,108,700 and growing. However I wish for it to show as 1,657,108k

Does javascript or html have a build in function to do this?

The value is being set throu javascript to a span field in html.

[edit]

From the comment I got my method as far as:

var start = '1,657,108,700';                
start = (start / 1000).toFixed(0);                                      
var finish = '';
while (start.length > 3)
{       
    finish = ','.concat(start.substring(start.length - 3, 3), finish);      
    start = start.substring(0, start.length - 3);
};
finish = start + finish + "k";
return finish;

however this returns 1,65,7k instead of 1,657,108k.. anyone know why?

Theun Arbeider
  • 5,259
  • 11
  • 45
  • 68
  • possible duplicates: http://stackoverflow.com/questions/2134161/format-number-like-stackoverflow-rounded-to-thousands-with-k-suffix , http://stackoverflow.com/questions/3177855/how-to-format-numbers-similar-to-stack-overflow-reputation-format – Andrei Sfat May 31 '11 at 07:07
  • @Andrei Sfat: this is in no way duplicates of either of them. The first is C# and my question is for javascript. The second method returns NaNk for me. – Theun Arbeider May 31 '11 at 07:19
  • No function that I know of, but it would be trivial to implement. Just divide by 1000, do Math.floor (or round) then append a 'k' to it. – beatgammit May 31 '11 at 07:31
  • what about this link? : http://stackoverflow.com/questions/2685911/is-there-a-way-round-numbers-into-a-friendly-format-e-g-1-1k – Andrei Sfat May 31 '11 at 07:45
  • @Andrei Sfat: Thank you, but that doesn't help either. – Theun Arbeider May 31 '11 at 07:59

1 Answers1

1
var formattedNumber = Math.round(yourNumber / 1000).toLocaleString() + "k";

Turn the above into a function or not as appropriate. I'm not aware of a single function to do this, or of a way to cater for non-English versions of "k" (assuming there are some), but at least toLocaleString() should take care of the comma versus fullstop for thousands issue.

UPDATE: I posted the above without testing it; when I tried it out I found toLocaleString() formatted 1234 as 1,234.00. I had thought of fixing it by using a regex replace to remove trailing zeros except of course I can't be sure what character toLocaleString() is going to use for the decimal point, so that won't work. I guess you could write some code that uses toLocaleString() on a "control" number (e.g., 1.1) to see at runtime what character it uses for the decimal.

UPDATE 2 for your updated question, inserting the commas manually, I did it like this:

var unformattedNumber = 123456;
var a = unformattedNumber.toString().split("");
for (var i=a.length-3; i >0; i-=3)
   a.splice(i,0,",");
var formattedNumber = a.join("") + "k";
nnnnnn
  • 147,572
  • 30
  • 200
  • 241