1

I have this string

17.12121

and I want to save it only as

17.12

I have try to use this command :

answer = String.format("%.2f", str1);

but he give an exception

java.util.IllegalFormatConversionException: f != java.lang.String

why ?

in the end I wnat the answer to be x.xx

Thanks ,

Korenron
  • 101
  • 2
  • 10

3 Answers3

1

To use %f you should to have a float not a String, instead you can use :

answer = String.format("%.2f", Float.valueOf(str1));
                               ^^^^^^^^^^^^^^^^^^^

Note that the format follow the Locale, so the dot can be converted to , the result can be 17,12 instead of 17.12 to make sure you get dot you can use Locale.US like this :

answer = String.format(Locale.US, "%.2f", Float.valueOf(str1));
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

If you want to use float formatting, you could parse your string as a float, and then use "%.2f.

If you just want to cut your string two places after the decimal point, you could just find the . character and take a substring based on its position.

int index = str1.indexOf('.');
if (index >= 0) {
    answer = str1.substring(0, index+3);
} else {
    answer = str1;
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
0
BigDecimal d= new BigDecimal("17.12121").setScale(2, RoundingMode.DOWN);
System.out.println(d);
Tobias Reich
  • 4,952
  • 3
  • 47
  • 90
Debapriya Biswas
  • 1,079
  • 11
  • 23