简体   繁体   English

.toFixed()数字(如果元素太大)

[英].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. 该数字小于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? 如果元素的宽度开始截断文本,将数字从“ 2,643,977”更改为“ 2.6M”的最佳方法是什么,因此假设100px可以显示2,643,977,但减少到50px显示260万?

Question Clarification 问题澄清

The text element is a percentage, therefore smaller screens will cut of large numbers. 文本元素是一个百分比,因此较小的屏幕将切出较大的数字。

  1. Is there a way obtain the inner elements text size? 有没有办法获取内部元素的文字大小?
  2. On this inner text width being greater than element width, shorten the number, be it 1,000 - 1k, 1,000,000 - 1m... 在此内部文本宽度大于元素宽度的情况下,缩短数字,例如1,000-1k,1,000,000-1m ...

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. 您可以使用如下所示的js函数来检查内容是否过宽,然后使用其他答案中提供的函数之一将其缩短。

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). 此函数接受要检查的文本,要限制为px的宽度以及实际元素使用的css类(以空格分隔)。 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;
}

How about this: 这个怎么样:

n2Display = (n<1000000) ? n : (n/1000000).toFixed(1) + 'M';

I'm assuming that n is a number, not a string here 我假设n是一个数字,而不是这里的字符串

function shorten(n){
  var l=Math.floor(n.length/3-1);
  return n.slice(0,n.length-l*3)+["","k","M","B"][l];
}

alert(shorten("123456"));
alert(shorten("123456789123"));

Note that this requires a String from Int to be passed. 请注意,这需要传递来自Int的字符串。

It simply cuts off every block of 3 numbers and replaces it with its shortform: 它简单地切断每个3个数字的块,并用其缩写形式代替它:

123,456 => 123k
123,456,789 => 123M

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM