2015-04-21 11 views
5

Diciamo che voglio stampare il numero 100000000. A prima vista è difficile dire quanti milioni questo numero rappresenta. Sono 10 milioni o 100 milioni? Come posso rendere più leggibili i grandi numeri in Java? Qualcosa di simile ad esempio sarebbe fantastico: 100 000 000. Puoi dire subito che il numero è 100 milioni.Come aggiungere uno spazio vuoto all'interno di int?

+0

È possibile utilizzare il trattino di sottolineatura per il numero grande. – Masudul

+0

@Masud OP vuole aggiungere spazi bianchi quando si stampa il numero, non nel codice sorgente – Turing85

+5

https://docs.oracle.com/javase/tutorial/java/data/numberformat.html – bobwah

risposta

9

Potete anche provare DecimalFormat;

DecimalFormat formatter = new DecimalFormat("#,###"); 
System.out.println(formatter.format(100000)); 

Risultati:

1000>>1,000 
10000>>10,000 
100000>>100,000 
1000000>>1,000,000 
0

Probabilmente vorrete semplicemente usare una stringa per questo. Se è necessario eseguire alcuni calcoli, è sufficiente mantenerlo come int finché non è necessario stamparlo. Quindi, quando è necessario stamparlo, convertirlo in una stringa, elaborare la stringa in modo che sia leggibile come si desidera e stamparla.

3

Si può provare in questo modo:

String.format("%.2fM", yourNumber/ 1000000.0); 

Questo mostrerà i numeri nel formato

1,000,000 => 1.00M 
1,234,567 => 1.23M 

EDIT: -

So che è un modifica tardi, ma sì, ci è un altro modo:

private static String[] suff = new String[]{"","k", "m", "b", "t"}; 
private static int MAX_LENGTH = 4; 

private static String numberFormat(double d) { 
    String str = new DecimalFormat("##0E0").format(d); 
    str = str.replaceAll("E[0-9]", suff[Character.getNumericValue(str.charAt(str.length() - 1))/3]); 
    while(str.length() > MAX_LENGTH || str.matches("[0-9]+\\.[a-z]")){ 
     str = str.substring(0, str.length()-2) + str.substring(str.length() - 1); 
    } 
    return str; 
} 

chiamata questa funzione e si otterrà l'output come segue:

201700 = 202k 
3000000 = 3m 
8800000 = 8.8m 
1

È possibile utilizzare formato decimale per formattare la stringa

DecimalFormat decimalFormat = new DecimalFormat("###,###,###"); 
    System.out.println(decimalFormat.format(100000000)); 

Questo stamperà 100.000.000

Per altro ingresso - dicono 1000 sarebbe stampare 1.000

2

Utilizzare la classe DecimalFormat, vedere il collegamento per le modalità di utilizzo.

Per salvare te la ricerca Ho scritto quello che fondamentalmente bisogno

DecimalFormat myFormatter = new DecimalFormat("### ### ###"); 
String output = myFormatter.format(value); 
System.out.println(output); 
0

come su di sotto approccio, ma it's supported in Java 7 e versioni successive:

int twoMillion = 2_000_000;

Problemi correlati