Is there a "reverse" function for d3.format?

I am looking for an inverse function for

d3.format(".3s")

(1)

function without success.

This function (1) gets a number and formats it with a metric prefix

examples:

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

      

What I need is a function that does the opposite: get a metric prefixed string and return a number

I am not asking for a possible implementation, but if you have one, it is appreciated. I ask if there is something already in d3. I searched for it in d3 and didn't find anything.

+3


source to share


2 answers


So here it is:



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;
}

      

+4


source


I found that susanoobit's excellent answer (which helped me a lot) didn't work in IE9 because it's built on ECMA 6. So here's a rebuild of it that should work in older browsers or 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;
        }

      

+1


source







All Articles