0

I am trying to convert a String number to two decimal places in Java. I saw lot of posts on satckoverflow but somehow I am getting an exception.

String number = "1.9040409535344458";
String result = String.format("%.2f", number);

System.out.println(result);

This is the exception I am getting -

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

I would like to have 1.904 as the output. Does anyone know what wrong I am doing here?

Community
  • 1
  • 1
john
  • 11,311
  • 40
  • 131
  • 251
  • Your number variable is String instead double or float. – Petar Butkovic Sep 20 '14 at 19:43
  • 2
    Convert the string to a number and then use the format. – Henry Sep 20 '14 at 19:43
  • I did that also `String.format("%.2f", Integer.parseInt(number));` and this time I am getting an exception as `java.lang.NumberFormatException: For input string: "1.9040409535344458"` – john Sep 20 '14 at 19:44
  • Because number is not an integer, but a float/double Edit: you should use `Double.parseDouble(number)` instead. – Kulu Limpa Sep 20 '14 at 19:45

4 Answers4

1

You can try using a NumberFormat. For example:

String number = "1.9040409535344458";
NumberFormat formatter = new DecimalFormat("#0.000"); 
String result = formatter.format(Double.valueOf(number));

System.out.println(result);
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

Just declare number to be double :

Double number = 1.9040409535344458;

instead of

String number = "1.9040409535344458";

OUTPUT :

1.90
afzalex
  • 8,598
  • 2
  • 34
  • 61
0

You are using a format not meant for a String. I would recommend either converting your String to a double or storing it as a double in the first place. Convert the String to a double, and pass that double to String.format.

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Armek
  • 1
  • 2
0

you should first convert the string into double and then change the decimal value

String number = "1.9040409535344458";
double result = Double.parseDouble(number);//converts the string into double
result = result *100;//adjust the decimal value
System.out.println(result);