2017-04-17 79 views
3

我在尋找一個反向功能d3.format是否有「反向」功能?

d3.format(".3s")(1)

function沒有成功。

此功能(1)得到一個編號,並使用metric prefix

例子格式化:

var f = d3.format(".3s"); 
f(42000); // "420k" 
f(0.0042); // "4,20µ" 

什麼,我想要的是正好相反的功能:得到公制前綴,並返回一個字符串一些

我不要求對可能實現的,但如果你有一些,這是值得歡迎的。我在問d3中是否有某些東西已經完成了。 我在d3中搜索到它,什麼也沒找到。

回答

4

那麼,它就在那裏:

let transformation = { 
    Y: Math.pow(10, 24), 
    Z: Math.pow(10, 21), 
    E: Math.pow(10, 18), 
    P: Math.pow(10, 15), 
    T: Math.pow(10, 12), 
    G: Math.pow(10, 9), 
    M: Math.pow(10, 6), 
    k: Math.pow(10, 3), 
    h: Math.pow(10, 2), 
    da: Math.pow(10, 1), 
    d: Math.pow(10, -1), 
    c: Math.pow(10, -2), 
    m: Math.pow(10, -3), 
    μ: Math.pow(10, -6), 
    n: Math.pow(10, -9), 
    p: Math.pow(10, -12), 
    f: Math.pow(10, -15), 
    a: Math.pow(10, -18), 
    z: Math.pow(10, -21), 
    y: Math.pow(10, -24) 
} 

let reverse = s => { 
    let returnValue; 
    Object.keys(transformation).some(k => { 
     if (s.indexOf(k) > 0) { 
      returnValue = parseFloat(s.split(k)[0]) * transformation[k]; 
      return true; 
     } 
    }) 
    return returnValue; 
} 
1

我發現susanoobit的出色答卷(這對我幫助很大)在IE9沒有工作,因爲它是建立在ECMA 6.所以這裏有一個重建起來那應該在舊版瀏覽器或IE中工作。

 var transformation = { 
      Y: Math.pow(10, 24), 
      Z: Math.pow(10, 21), 
      E: Math.pow(10, 18), 
      P: Math.pow(10, 15), 
      T: Math.pow(10, 12), 
      G: Math.pow(10, 9), 
      M: Math.pow(10, 6), 
      k: Math.pow(10, 3), 
      h: Math.pow(10, 2), 
      da: Math.pow(10, 1), 
      d: Math.pow(10, -1), 
      c: Math.pow(10, -2), 
      m: Math.pow(10, -3), 
      μ: Math.pow(10, -6), 
      n: Math.pow(10, -9), 
      p: Math.pow(10, -12), 
      f: Math.pow(10, -15), 
      a: Math.pow(10, -18), 
      z: Math.pow(10, -21), 
      y: Math.pow(10, -24) 
     } 


     function reverse(str) { 
      var returnValue = -1; 
      var tempArr = d3.entries(transformation); 
      tempArr.forEach(function(d){ 
      if (str.indexOf(d.key)!=-1) { 
       returnValue = parseFloat(str) * d.value; 
       return true; 
      } 

      }) 
      return returnValue; 
     }