Converting floats to short approximations

I needed this in a project I'm working on and wrote this function which seems to work quite well, (haven't tested it extensively though)

String nufix(float n) { // Numerical Suffix
  String a="";          // String manipulation variable
  float K = 1000.0;     // Kilo
  float M = pow(K, 2);  // Mega
  float G = pow(K, 3);  // Giga
  float T = pow(K, 4);  // Terra
  float P = pow(K, 5);  // Peta
  float E = pow(K, 6);  // Exa
  float Z = pow(K, 7);  // Zeta
  float Y = pow(K, 8);  // Yotta
  float sv=1.0;         // Suffix value
  char  sc=' ';         // Suffix char
  int neg=0; if (n<0){neg=1;} // boolean as int for convenience

  if      (abs(n) < 1) {return '.'+str(int(n*10));}
  else if (abs(n) < K) {return str(int(n));}
  else if (abs(n) < M) {sc='K'; sv=K;}
  else if (abs(n) < G) {sc='M'; sv=M;}
  else if (abs(n) < T) {sc='G'; sv=G;}
  else if (abs(n) < P) {sc='T'; sv=T;}
  else if (abs(n) < E) {sc='P'; sv=P;}
  else if (abs(n) < Z) {sc='E'; sv=E;}
  else if (abs(n) < Y) {sc='Z'; sv=Z;}
  else if (abs(n) < Y*K) {sc='Y'; sv=Y;}
  else {return "yo mama";} // here I give up

  if (abs(n)>=10.0*sv) {
  return str(int(n/sv))+sc;
  }
  else {
    a=str(n/sv);
    if (a.charAt(1+neg)=='.' && a.charAt(2+neg)=='0') {
      return a.substring(0,1+neg)+sc;
      }
    else {return a.substring(0,3+neg)+sc;}
  }
}

Also this shorter but a little worse variant

String nufix(float n) { 
  String scrs="KMGTPEZY";
  if      (abs(n) < 1) {return '.'+str(int(n*10));}
  else if (abs(n) < 1000.0) {return str(int(n));}
  for(int i=0; i<scrs.length();i++)
  {
    if (abs(n) < pow(1000.0,i+2)){
      return str(int(n/pow(K,i+1)))+scrs.charAt(i);
    }
  }
  return "yo mama";
}

Answers

  • Answer ✓

    Factor K in line 8 of your second code needs to be changed for 1000. You can see you have a bug with the sign symbol. Check by running the following code. I rename your first function nufix1() and your second nufix2():

    Kf

    void setup() {
      noLoop();
      FloatList fl=new FloatList();
    
      fl.append(0);
      for (int i=0; i<32; i++) {
        fl.append(pow(2, i)/10.0);
        fl.append(-pow(2, i)/10.0);
      }
      fl.sort();
    
      println("Index\tFloat\tVers1\tVers2");
      int ctr=0;
      for (float f : fl)
        println(ctr++ +"\t"+f+"\t"+nufix1(f)+"\t"+nufix2(f));
    }
    
Sign In or Register to comment.