Come formattare ben numeri floating a stringa senza inutili decimali 0?
-
22-08-2019 - |
Domanda
Un doppio 64-bit possono rappresentare intero +/- 2 53 esattamente
Dato questo fatto ho scelto di utilizzare un doppio tipo come un unico tipo per tutti i miei tipi, dal momento che la mia più grande intero è senza segno a 32 bit.
Ma ora devo stampare questi numeri interi pseudo, ma il problema è che sono anche mescolati con doppie attuali.
Quindi, come faccio a stampare questi raddoppia bene in Java?
Ho cercato String.format("%f", value)
, che è vicino, tranne ho un sacco di zeri finali per piccoli valori.
Ecco un esempio di output di di %f
232.00000000 0.18000000000 1237875192.0 4.5800000000 0.00000000 1.23450000
Quello che voglio è:
232 0.18 1237875192 4.58 0 1.2345
Certo che posso scrivere una funzione per tagliare quegli zeri, ma questo è molto perdita di prestazioni a causa di manipolazione di stringhe. Posso fare meglio con un altro codice di formato?
Modifica
Le risposte di Tom E. e Jeremy S. sono inaccettabili in quanto entrambi i turni arbitrariamente a 2 cifre decimali. Si prega di capire il problema prima di rispondere.
Modifica 2
Si prega di notare che String.format(format, args...)
è dipendente dal luogo (vedi risposte qui sotto).
Soluzione
Se l'idea è quella di stampare interi memorizzati come doppie come se fossero numeri interi, e comunque stampare i doppi con il minimo di precisione necessaria:
public static String fmt(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
produce:
232
0.18
1237875192
4.58
0
1.2345
e non si basa sulla manipolazione delle stringhe.
Altri suggerimenti
new DecimalFormat("#.##").format(1.199); //"1.2"
Come sottolineato nei commenti, questa non è la risposta giusta alla domanda iniziale.
Detto questo, è un modo molto utile per formattare numeri senza zeri finali inutili.
String.format("%.2f", value) ;
In breve:
Se si vuole sbarazzarsi di zeri finali e dei problemi Locale, quindi si dovrebbe utilizzare:
double myValue = 0.00000021d;
DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
System.out.println(df.format(myValue)); //output: 0.00000021
Spiegazione:
Perché le altre risposte non mi andava:
-
Double.toString()
oSystem.out.println
oFloatingDecimal.toJavaFormatString
utilizza notazione scientifica se doppia è inferiore a 10 ^ -3 o superiore o uguale a 10 ^ 7double myValue = 0.00000021d; String.format("%s", myvalue); //output: 2.1E-7
-
utilizzando
%f
, la precisione decimale di default è 6, altrimenti si può hardcode esso, ma si traduce in zeri extra aggiunti se hai meno decimali. Esempio:double myValue = 0.00000021d; String.format("%.12f", myvalue); //output: 0.000000210000
-
utilizzando
setMaximumFractionDigits(0);
o%.0f
di rimuovere qualsiasi precisione decimale, che va bene per gli interi / anela, ma non per il doppiodouble myValue = 0.00000021d; System.out.println(String.format("%.0f", myvalue)); //output: 0 DecimalFormat df = new DecimalFormat("0"); System.out.println(df.format(myValue)); //output: 0
-
utilizzando DecimalFormat, sei locali dipendenti. Nel locale francese, il separatore decimale è una virgola, non un punto:
double myValue = 0.00000021d; DecimalFormat df = new DecimalFormat("0"); df.setMaximumFractionDigits(340); System.out.println(df.format(myvalue));//output: 0,00000021
Uso della locale inglese fa in modo di ottenere un punto per separatore decimale, ovunque il programma verrà eseguito
Perché usare 340 poi per setMaximumFractionDigits
?
Due motivi:
-
setMaximumFractionDigits
accetta un numero intero, ma la sua attuazione ha una cifra massima consentita diDecimalFormat.DOUBLE_FRACTION_DIGITS
pari 340 -
Double.MIN_VALUE = 4.9E-324
così con 340 cifre si è sicuri di non arrotondare la vostra precisione doppia e sciolto
Perché non:
if (d % 1.0 != 0)
return String.format("%s", d);
else
return String.format("%.0f",d);
Questo dovrebbe funzionare con i valori estremi supportati da Double. I rendimenti:
0.12
12
12.144252
0
I miei 2 centesimi:
if(n % 1 == 0) {
return String.format(Locale.US, "%.0f", n));
} else {
return String.format(Locale.US, "%.1f", n));
}
Sulla mia macchina, la seguente funzione è di circa 7 volte più veloce rispetto alla funzione fornita da di JasonD risposta , in quanto evita String.format
:
public static String prettyPrint(double d) {
int i = (int) d;
return d == i ? String.valueOf(i) : String.valueOf(d);
}
No, non importa.
perdita di prestazioni a causa della manipolazione stringa è pari a zero.
Ed ecco il codice per tagliare alla fine dopo %f
private static String trimTrailingZeros(String number) {
if(!number.contains(".")) {
return number;
}
return number.replaceAll("\\.?0*$", "");
}
if (d == Math.floor(d)) {
return String.format("%.0f", d);
} else {
return Double.toString(d);
}
Si prega di notare che String.format(format, args...)
è dipendente dal luogo perché formatta utilizzando impostazioni internazionali predefinite dell'utente, che è, probabilmente con le virgole e anche gli spazi dentro come 123 456.789 o 123,456.789 , che può essere non è esattamente quello che ci si aspetta.
Si può preferire di usare String.format((Locale)null, format, args...)
.
Ad esempio,
double f = 123456.789d;
System.out.println(String.format(Locale.FRANCE,"%f",f));
System.out.println(String.format(Locale.GERMANY,"%f",f));
System.out.println(String.format(Locale.US,"%f",f));
stampe
123456,789000
123456,789000
123456.789000
e questo è ciò che String.format(format, args...)
fare in diversi paesi.
EDIT Ok, dal momento che v'è stata una discussione su formalità:
res += stripFpZeroes(String.format((Locale) null, (nDigits!=0 ? "%."+nDigits+"f" : "%f"), value));
...
protected static String stripFpZeroes(String fpnumber) {
int n = fpnumber.indexOf('.');
if (n == -1) {
return fpnumber;
}
if (n < 2) {
n = 2;
}
String s = fpnumber;
while (s.length() > n && s.endsWith("0")) {
s = s.substring(0, s.length()-1);
}
return s;
}
Ho fatto una DoubleFormatter
per convertire in modo efficiente un gran numero di valori doppi per un bel stringa / presentabile:
double horribleNumber = 3598945.141658554548844;
DoubleFormatter df = new DoubleFormatter(4,6); //4 = MaxInteger, 6 = MaxDecimal
String beautyDisplay = df.format(horribleNumber);
- Se la parte intera di V ha più di MaxInteger => visualizzazione V in formato scienziato (1.2345e + 30) altrimenti visualizzare modalita' 124,45,678 mila.
- il MaxDecimal decidere il numero di cifre decimali (assetto con arrotondamento del banchiere)
Ecco il codice:
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
/**
* Convert a double to a beautiful String (US-local):
*
* double horribleNumber = 3598945.141658554548844;
* DoubleFormatter df = new DoubleFormatter(4,6);
* String beautyDisplay = df.format(horribleNumber);
* String beautyLabel = df.formatHtml(horribleNumber);
*
* Manipulate 3 instances of NumberFormat to efficiently format a great number of double values.
* (avoid to create an object NumberFormat each call of format()).
*
* 3 instances of NumberFormat will be reused to format a value v:
*
* if v < EXP_DOWN, uses nfBelow
* if EXP_DOWN <= v <= EXP_UP, uses nfNormal
* if EXP_UP < v, uses nfAbove
*
* nfBelow, nfNormal and nfAbove will be generated base on the precision_ parameter.
*
* @author: DUONG Phu-Hiep
*/
public class DoubleFormatter
{
private static final double EXP_DOWN = 1.e-3;
private double EXP_UP; // always = 10^maxInteger
private int maxInteger_;
private int maxFraction_;
private NumberFormat nfBelow_;
private NumberFormat nfNormal_;
private NumberFormat nfAbove_;
private enum NumberFormatKind {Below, Normal, Above}
public DoubleFormatter(int maxInteger, int maxFraction){
setPrecision(maxInteger, maxFraction);
}
public void setPrecision(int maxInteger, int maxFraction){
Preconditions.checkArgument(maxFraction>=0);
Preconditions.checkArgument(maxInteger>0 && maxInteger<17);
if (maxFraction == maxFraction_ && maxInteger_ == maxInteger) {
return;
}
maxFraction_ = maxFraction;
maxInteger_ = maxInteger;
EXP_UP = Math.pow(10, maxInteger);
nfBelow_ = createNumberFormat(NumberFormatKind.Below);
nfNormal_ = createNumberFormat(NumberFormatKind.Normal);
nfAbove_ = createNumberFormat(NumberFormatKind.Above);
}
private NumberFormat createNumberFormat(NumberFormatKind kind) {
final String sharpByPrecision = Strings.repeat("#", maxFraction_); //if you do not use Guava library, replace with createSharp(precision);
NumberFormat f = NumberFormat.getInstance(Locale.US);
//Apply banker's rounding: this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a sequence of calculations
f.setRoundingMode(RoundingMode.HALF_EVEN);
if (f instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) f;
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
//set group separator to space instead of comma
//dfs.setGroupingSeparator(' ');
//set Exponent symbol to minus 'e' instead of 'E'
if (kind == NumberFormatKind.Above) {
dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
} else {
dfs.setExponentSeparator("e");
}
df.setDecimalFormatSymbols(dfs);
//use exponent format if v is out side of [EXP_DOWN,EXP_UP]
if (kind == NumberFormatKind.Normal) {
if (maxFraction_ == 0) {
df.applyPattern("#,##0");
} else {
df.applyPattern("#,##0."+sharpByPrecision);
}
} else {
if (maxFraction_ == 0) {
df.applyPattern("0E0");
} else {
df.applyPattern("0."+sharpByPrecision+"E0");
}
}
}
return f;
}
public String format(double v) {
if (Double.isNaN(v)) {
return "-";
}
if (v==0) {
return "0";
}
final double absv = Math.abs(v);
if (absv<EXP_DOWN) {
return nfBelow_.format(v);
}
if (absv>EXP_UP) {
return nfAbove_.format(v);
}
return nfNormal_.format(v);
}
/**
* format and higlight the important part (integer part & exponent part)
*/
public String formatHtml(double v) {
if (Double.isNaN(v)) {
return "-";
}
return htmlize(format(v));
}
/**
* This is the base alogrithm: create a instance of NumberFormat for the value, then format it. It should
* not be used to format a great numbers of value
*
* We will never use this methode, it is here only to understanding the Algo principal:
*
* format v to string. precision_ is numbers of digits after decimal.
* if EXP_DOWN <= abs(v) <= EXP_UP, display the normal format: 124.45678
* otherwise display scientist format with: 1.2345e+30
*
* pre-condition: precision >= 1
*/
@Deprecated
public String formatInefficient(double v) {
final String sharpByPrecision = Strings.repeat("#", maxFraction_); //if you do not use Guava library, replace with createSharp(precision);
final double absv = Math.abs(v);
NumberFormat f = NumberFormat.getInstance(Locale.US);
//Apply banker's rounding: this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a sequence of calculations
f.setRoundingMode(RoundingMode.HALF_EVEN);
if (f instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) f;
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
//set group separator to space instead of comma
dfs.setGroupingSeparator(' ');
//set Exponent symbol to minus 'e' instead of 'E'
if (absv>EXP_UP) {
dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
} else {
dfs.setExponentSeparator("e");
}
df.setDecimalFormatSymbols(dfs);
//use exponent format if v is out side of [EXP_DOWN,EXP_UP]
if (absv<EXP_DOWN || absv>EXP_UP) {
df.applyPattern("0."+sharpByPrecision+"E0");
} else {
df.applyPattern("#,##0."+sharpByPrecision);
}
}
return f.format(v);
}
/**
* Convert "3.1416e+12" to "<b>3</b>.1416e<b>+12</b>"
* It is a html format of a number which highlight the integer and exponent part
*/
private static String htmlize(String s) {
StringBuilder resu = new StringBuilder("<b>");
int p1 = s.indexOf('.');
if (p1>0) {
resu.append(s.substring(0, p1));
resu.append("</b>");
} else {
p1 = 0;
}
int p2 = s.lastIndexOf('e');
if (p2>0) {
resu.append(s.substring(p1, p2));
resu.append("<b>");
resu.append(s.substring(p2, s.length()));
resu.append("</b>");
} else {
resu.append(s.substring(p1, s.length()));
if (p1==0){
resu.append("</b>");
}
}
return resu.toString();
}
}
Nota: ho usato 2 funzioni dalla libreria GUAVA. Se non si utilizza guava, il codice da soli:
/**
* Equivalent to Strings.repeat("#", n) of the Guava library:
*/
private static String createSharp(int n) {
StringBuilder sb = new StringBuilder();
for (int i=0;i<n;i++) {
sb.append('#');
}
return sb.toString();
}
Usa un DecimalFormat
e setMinimumFractionDigits(0)
Questo otterrà il lavoro fatto bene, so che l'argomento è vecchio, ma mi è stato alle prese con lo stesso problema fino a quando sono arrivato a questo. Spero che qualcuno sia utile.
public static String removeZero(double number) {
DecimalFormat format = new DecimalFormat("#.###########");
return format.format(number);
}
new DecimalFormat("00.#").format(20.236)
//out =20.2
new DecimalFormat("00.#").format(2.236)
//out =02.2
- 0 per il numero minimo di cifre
- rende # cifre
String s = String.valueof("your int variable");
while (g.endsWith("0") && g.contains(".")) {
g = g.substring(0, g.length() - 1);
if (g.endsWith("."))
{
g = g.substring(0, g.length() - 1);
}
}
risposta in ritardo ma ...
Hai detto che Menu per memorizzare i numeri con il doppia tipo . Penso che questo potrebbe essere la radice del problema, perché ti costringe a memorizzare interi in doppie (e quindi perdere le prime informazioni sulla natura del valore). Che dire di memorizzare i numeri in istanze del Numero classe (superclasse sia di doppio e intero) e si basano sul polimorfismo per determinare il corretto formato di ogni numero?
So che non può essere accettabile per il refactoring tutta una parte del codice a causa di questo, ma potrebbe produrre l'output desiderato senza ulteriore codice / fusione / parsing.
Esempio:
import java.util.ArrayList;
import java.util.List;
public class UseMixedNumbers {
public static void main(String[] args) {
List<Number> listNumbers = new ArrayList<Number>();
listNumbers.add(232);
listNumbers.add(0.18);
listNumbers.add(1237875192);
listNumbers.add(4.58);
listNumbers.add(0);
listNumbers.add(1.2345);
for (Number number : listNumbers) {
System.out.println(number);
}
}
}
produrrà il seguente output:
232
0.18
1237875192
4.58
0
1.2345
public static String fmt(double d) {
String val = Double.toString(d);
String[] valArray = val.split("\\.");
long valLong = 0;
if(valArray.length == 2){
valLong = Long.parseLong(valArray[1]);
}
if (valLong == 0)
return String.format("%d", (long) d);
else
return String.format("%s", d);
}
Ho dovuto usare questa causa d == (long)d
mi stava dando violazione nella relazione del sonar
Questo è ciò che mi si avvicinò con:
private static String format(final double dbl) {
return dbl % 1 != 0 ? String.valueOf(dbl) : String.valueOf((int) dbl);
}
Semplice uno di linea, getta solo a int se davvero bisogno di
Qui ci sono due modi per realizzarla. In primo luogo, il modo più breve (e probabilmente meglio):
public static String formatFloatToString(final float f)
{
final int i=(int)f;
if(f==i)
return Integer.toString(i);
return Float.toString(f);
}
Ed ecco il più a lungo e così probabilmente peggiore:
public static String formatFloatToString(final float f)
{
final String s=Float.toString(f);
int dotPos=-1;
for(int i=0;i<s.length();++i)
if(s.charAt(i)=='.')
{
dotPos=i;
break;
}
if(dotPos==-1)
return s;
int end=dotPos;
for(int i=dotPos+1;i<s.length();++i)
{
final char c=s.charAt(i);
if(c!='0')
end=i+1;
}
final String result=s.substring(0,end);
return result;
}
Ecco una risposta che funziona davvero (combinazione di risposte diverse qui)
public static String removeTrailingZeros(double f)
{
if(f == (int)f) {
return String.format("%d", (int)f);
}
return String.format("%f", f).replaceAll("0*$", "");
}
So che questo è un filo molto vecchio .. Ma penso che il modo migliore per farlo è il seguente:
public class Test {
public static void main(String args[]){
System.out.println(String.format("%s something",new Double(3.456)));
System.out.println(String.format("%s something",new Double(3.456234523452)));
System.out.println(String.format("%s something",new Double(3.45)));
System.out.println(String.format("%s something",new Double(3)));
}
}
Output:
3.456 something
3.456234523452 something
3.45 something
3.0 something
L'unico problema è l'ultimo in cui 0,0 non viene rimosso. Ma se siete in grado di vivere con quella, allora questo funziona meglio. % .2f sarà arrotondare per le ultime 2 cifre decimali. Così si DecimalFormat. Se avete bisogno di tutte le cifre decimali ma non gli zeri finali, allora questo funziona meglio.
String s = "1.210000";
while (s.endsWith("0")){
s = (s.substring(0, s.length() - 1));
}
Questo renderà la stringa di abbandonare il tailing 0-s.