marks you error "number is String", since you need to convert the String to a numeric value, you can do it in this way converting the value of String
to Double
or Float
by Double.parseDouble(numero)
or through Float.parseFloat(numero)
:
String numero = "59.2348837";
String resultado = String.format( "%.2f", Float.parseFloat(numero));
There is a similar question
Show number with two decimals
but in this case you can convert the value of String to Double by Double.parseDouble(numero)
, example:
String numero = "59.2348837";
DecimalFormat df = new DecimalFormat("0.00");
String resultado = df.format(Double.parseDouble(numero));
result will have the value:
59.23
You can even use a method with the above described to obtain the value you require:
private static String getTwoDecimals(String valor){
DecimalFormat df = new DecimalFormat("0.00");
return df.format(Double.parseDouble(valor));
}
and you call it this way:
String numero = "59.2348837";
String resultado = getTwoDecimals(numero);
to obtain as a result value:
59.23