john
john

Reputation: 11709

How to convert a String number to two three decimal places in Java?

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?

Upvotes: 0

Views: 1178

Answers (4)

Armek
Armek

Reputation: 1

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.

Upvotes: 0

Abhishek Chawla
Abhishek Chawla

Reputation: 46

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);

Upvotes: 0

afzalex
afzalex

Reputation: 8652

Just declare number to be double :

Double number = 1.9040409535344458;

instead of

String number = "1.9040409535344458";

OUTPUT :

1.90

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

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);

Upvotes: 1

Related Questions