
Originariamente inviata da
antonello2
Mi puoi spiegare come fare ?

Originariamente inviata da
antonello2
Troppo complicato ?
No, complicato non lo è.
Puoi farti innanzitutto una piccola classe del tipo (scritta al volo, puoi fare varianti come vuoi):
codice:
public class NumberConverter {
private NumberFormat numberFormat;
public NumberConverter(NumberFormat numberFormat) {
this.numberFormat = numberFormat;
}
public String formatDouble(double val) {
return numberFormat.format(val);
}
public double parseDouble(String str) {
if (str == null || str.length() == 0) {
throw new NumberFormatException("String not parsable as double");
}
ParsePosition pp = new ParsePosition(0);
Number n = numberFormat.parse(str, pp);
if (pp.getIndex() != str.length()) {
throw new NumberFormatException("String not parsable as double");
}
return n.doubleValue();
}
}
C'è un motivo per il fatto che il parseDouble è un pochino più lungo e "forbito". Il fatto è che il semplice parse(String) non è così "stretto" come molti possono pensare. La sua documentazione infatti dice "The method may not use the entire text of the given string.".
Se ad esempio il Locale del NumberFormat è ITALIAN e si fa nf.parse("123.45") (notare il punto messo per sbaglio), si ottiene 123 (intero!) senza avere eccezioni. Quel parse funziona così ..... non è baco.
Allora si sfrutta anche ParsePosition per validare che il parsing usi tutta la stringa.
Crei innanzitutto un NumberFormat:
codice:
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(0);
nf.setMaximumFractionDigits(2);
nf.setGroupingUsed(false);
Il NumberFormat ha il Locale "predefinito". Se la macchina ha il locale italiano, l'utente dovrà inserire es. "123,45", se il locale inglese "123.45" ecc...
Quindi per finire:
codice:
NumberConverter convertitore = new NumberConverter(nf);
e quindi userai i suoi formatDouble e parseDouble.