I always like input in my function to get numbers that range from 0.1 to 999.9 (the decimal part is always separated by '.', if there is no decimal then there is no '.' for example 9 or 7 .
How do I convert this String to float value regardless of localization (some countries use ',' to separate decimal part of number. I always get it with the 开发者_Python百科'.')? Does this depend on local computer settings?
The Float.parseFloat()
method is not locale-dependent. It expects a dot as decimal separator. If the decimal separator in your input is always dot, you can use this safely.
The NumberFormat
class provides locale-aware parse and format should you need to adapt for different locales.
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
DecimalFormat format = new DecimalFormat("0.#");
format.setDecimalFormatSymbols(symbols);
float f = format.parse(str).floatValue();
valueStr = valueStr.replace(',', '.');
return new Float(valueStr);
Done
See java.text.NumberFormat
and DecimalFormat
:
NumberFormat nf = new DecimalFormat ("990.0");
double d = nf.parse (text);
What about this:
Float floatFromStringOrZero(String s){
Float val = Float.valueOf(0);
try{
val = Float.valueOf(s);
} catch(NumberFormatException ex){
DecimalFormat df = new DecimalFormat();
Number n = null;
try{
n = df.parse(s);
} catch(ParseException ex2){
}
if(n != null)
val = n.floatValue();
}
return val;
}
You can use the placeholder %s-String for any primitive type.
float x = 3.15f, y = 1.2345f;
System.out.printf("%.4s and %.5s", x, y);
Output: 3.15 and 1.234
%s is always english formatting regardless of localization.
If you want a specif local formatting, you could also do:
import java.util.Locale;
float x = 3.15f, y = 1.2345f;
System.out.printf(Locale.GERMAN, "%.2f and %.4f", x, y);
Output: 3,15 and 1,2345
I hope this piece of code may help you.
public static Float getDigit(String quote){
char decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
String regex = "[^0-9" + decimalSeparator + "]";
String valueOnlyDigit = quote.replaceAll(regex, "");
if (String.valueOf(decimalSeparator).equals(",")) {
valueOnlyDigit = valueOnlyDigit.replace(",", ".");
//Log.i("debinf purcadap", "substituted comma by dot");
}
try {
return Float.parseFloat(valueOnlyDigit);
} catch (ArithmeticException | NumberFormatException e) {
//Log.i("debinf purcadap", "Error in getMoneyAsDecimal", e);
return null;
}
}
精彩评论