2010-09-09 16 views
8

Si tengo un número que es 100,000,000 ¿cómo puedo representar eso como "100M" en una cadena?¿Cómo formatear números largos?

+0

Surley esto es un duplicado ... – TheLQ

+0

Esto es similar, pero no es un duplicado: http://stackoverflow.com/questions/529432/java-format-number-in-millions –

+0

Aquí está una clase que hace algo similar: http://jcs.mobile-utopia.com/jcs/5242_ScaledNumberFormat.java, desafortunadamente no parece ser parte de una biblioteca compatible. – oksayt

Respuesta

7

Que yo sepa, no hay apoyo biblioteca para abreviar los números, pero se puede hacer fácilmente usted mismo:

NumberFormat formatter = NumberFormat.getInstance(); 
String result = null; 
if (num % 1000000 == 0 && num != 0) { 
    result = formatter.format(num/1000000) + "M"; 
} else if (num % 1000 == 0 && num != 0) { 
    result = formatter.format(num/1000) + "K"; 
} else { 
    result = formatter.format(num); 
} 

Por supuesto, esto supone que usted no desea acortar un número como 1,234,567.89. Si hace, entonces esta pregunta es duplicate.

+1

jeje, ¿y si num = 0? Gotcha! –

+0

¿Qué, "0M" no es válido? ;) –

2

Existe un algoritmo para hacer eso:

se necesita un mapa que se parece a

2 => "hundred" 
3 => "thousand" 
6 => "million" 
9 => "billion" 
12 => "trillion" 
15 => "quadrillion" 

... y así sucesivamente ...

1) Tome el número "num ", calcule el exponente log10" ex "del número y pégalo.

Atención

log10 (0) no existe a fin de comprobar que el número no es 0 y ya que no tiene sentido para demostrar algo como 20 = "2 diez" ¡debe devolver el número como está si es más pequeño que 100!

2) Ahora itere a través de las teclas del mapa hash anterior y busque si una clave coincide, si no toma la tecla que es menor que el exponente "ex".

3) ¡Actualice "ex" a esta tecla!

4) Ahora formato al número como

num = num/pow (10, ex)

(!! ex es una clave del mapa hash !!)

5) ahora usted podría redondear el número a una cierta precisión y la salida num + yourHash[ex]

un ejemplo:

number = 12345.45 
exponent = floor(log10(12345.45)) 

exponent should now be 4 ! 

look for a key in the hash map -- whoops no key matches 4 ! -- so take 3 ! 

set exponent to 3 

now you scale the number: 

number = number/pow(10, exponent) 

number = 12345.45/pow(10, 3) 

number = 12345.45/1000 

number is now 12.34545 

now you get the value to the corresponding key out of the hash map 

the value to the key, which is 3 in this example, is thousand 

so you output 12.34545 thousand 
0

aquí está mi solución para que sea un poco más genérica:

private static final String[] magnitudes = new String[] {"", "K", "M"}; 

public static String shortenNumber(final Integer num) { 
    if (num == null || num == 0) 
     return "0"; 

    float res = num; 
    int i = 0; 
    for (; i < magnitudes.length; i++) { 
     final float sm = res/1000; 
     if (sm < 1) break; 

     res = sm; 
    } 


    // don't use fractions if we don't have to 
    return ((res % (int) res < 0.1) ? 
       String.format("%d", (int)res) : 
       String.format("%.1f", res) 
      ) 
      + magnitudes[i]; 
} 
0

Esta es la solución más general.

public static String abbreviateNumber(long num) { 

    long temp = num/1000000; 
    if(temp > 0) { 
     return temp + "M+"; 
    } 

    temp = num/1000; 
    if (temp > 0) { 
     return temp + "K+"; 
    } 

    temp = num/500; 
    if (temp > 0) { 
     return "500+"; 
    } 

    temp = num/100; 
    if (temp > 0) { 
     return "100+"; 
    } 

    temp = num/50; 
    if (temp > 0) { 
     return "50+"; 
    } 

    temp = num/10; 
    if (temp > 0) { 
     return "10+"; 
    } 

    return String.valueOf(num); 
} 
Cuestiones relacionadas