truncate float Number - Android java.lang

Android examples for java.lang:Float

Description

truncate float Number

Demo Code

import java.text.DecimalFormat;

public class Main {

  private static final String[] TRUNCATE_NUMBER_SUFFIX = new String[] {
          "", "K", "M", "B", "T" };
  public static String truncateNumber(float number) {
    float max = (float) Math.pow(1000, TRUNCATE_NUMBER_SUFFIX.length);
    float min = -max;
    if (number >= max) {
      return "+";
    }/*from  w  w  w.ja  v  a 2s .  c  o  m*/
    if (number <= min) {
      return "-";
    }

    boolean isMinus = number < 0.0f;
    float num = isMinus ? -number : number;
    String s = "";
    for (int i = 0; i < TRUNCATE_NUMBER_SUFFIX.length; i++) {
      if (num / 1000f < 1f) {
        if (num / 100f < 1f) {
          s = new DecimalFormat("##.#").format(num);
        } else {
          s = new DecimalFormat("###").format(num);
        }
        s += TRUNCATE_NUMBER_SUFFIX[i];
        break;
      }
      num = num / 1000f;
    }
    return isMinus ? "-" + s : s;
  }

}

Related Tutorials