Q:

.toFixed() Number If Too Big For Element

There is a unique number displayed to users of particular groups on their account dashboard. This number is fetched from the database and changed frequently. The number is less than 10,000,000.
What would be the best way to change the number from let's say "2,643,977" to the likes of "2.6M" if the width of the element starts to cut off the text, so lets say 100px can show 2,643,977, but reduced to 50px it shows 2.6M?
Question Clarification
The text element is a percentage, therefore smaller screens will cut of large numbers.

Is there a way obtain the inner elements text size?
On this inner text width being greater than element width, shorten the number, be it 1,000 - 1k, 1,000,000 - 1m...

A:

You could use a js function like the following to check if your content is too wide, then use one of the functions provided in the other answers to shorten it if so.
This function accepts the text you want to check, the width you want to constrain it to in px, and the css classes your actual element uses (in a space-separated string).  It returns a bool indicating whether the text fits.
function checkIfFits(text, width, classes) {
  var s = document.createElement("span");
  s.className = classes;
  s.innerHTML = text;
  if (parseInt(s.offsetWidth, 10) > width) return false;
  return true;
}

