I will explain:
I have one String
in Java :
String numero = "59.2348837";
this is what i try to do:
String.format( "%.2f", numero)
And I try to get as a result:
String resultado = "59.23";
But it throws me an error because number is String
. The error pops up when I do the string format
.
How could I format that String
to 2 decimal places and have the result still be a String
?
It gives you an error "number is String", since you need to convert the String to a numerical value, you can do it this way by converting the value of
String
aDouble
orFloat
throughDouble.parseDouble(numero)
or throughFloat.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:result will have the value:
You can even use a method as described above to get the value you require:
and you call it this way:
to get as result value:
It is because the format
%.2f
is allowed for float. To format them you will have to convert thestring
tofloat
and then format it:The problem you are having is because in the format string, you are telling the method
String.format()
that what it will receive as the first parameter is a float number and when you pass it aString
it should throw an exception similar to this:To get around this, you just have to convert your string to a float number (float or double) and pass that number to the method. This is how it works for you:
If you only want 2 decimals you can also make a substring so you save double parsing from String to double and from double to String
I'll give you a quick example: