Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

d3.js - How to change D3.format to display real number suffix instead of Byte suffix

Newbie Alert! My experience with JavaScript and SVG is EXTREMELY dated and I am completely new to d3.

I've just learned that d3.format('s') will display a number like 160,000 to 160k and a number like 20,000,000,000 to 20G. AWESOME!! There is just one teeny-tiny problem. This is a format for Scientific Notation in Bytes. I assume (maybe incorrectly) there must be an additional parameter that d3 uses to display numbers in Thousands (16T) and Millions (160M) and Billions (20B) instead of Bytes. No?

I have found another question how to get localizable or customizable si codes with d3.format and have looked at other similar questions but have yet to find what I believe to be the real answer. If what I am trying to do is not a feature in d3 but there is a work-around, I might need a little help implementing it.

I have been stepping through the d3 code to try to understand how to use the the other input parameters, si codes, prefix, type, etc. and even tried to glean some information from a tutorial here: D3.format tutorial through examples

It's become pretty clear that one needs to be an expert in D3 alone. So, in the absence of time, I'm asking for a D3 guru to please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a custom formatting function adapted from another question:

function getFormatter(digits) {
  var notations = [
    // { value: 1E12, suffix: "T" }, what you'll use for trillion?
    { value: 1E9,  suffix: "B" },
    { value: 1E6,  suffix: "M" },
    { value: 1E3,  suffix: "T" }        
  ]

  rx = /.0+$|(.[0-9]*[1-9])0+$/

  return function(num) {
        var notation
    for (var i = 0; i < notations.length; i++) {
      notation = notations[i]
      if (num >= notation.value) {
        var value = num / notation.value
        value = value.toFixed(digits)
        value = value.replace(rx, "$1")
        return value + notation.suffix
      }
    }
  }
}


var numbers = [
  20000000000,
  160020,
  18200000
]

d3.select('body')
  .append('ul')
  .selectAll('li')
  .data(numbers)
  .enter()
  .append('li')
  .text(getFormatter(2))
span {
  display:
}
<script src="https://d3js.org/d3.v4.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...