public static void main(String args[]) { System.out.println(convert("5")); System.out.println(convert("56")); System.out.println(convert("560")); System.out.println(convert("5600")); } public static double convert(String str){ double asd=Double.valueOf(str); return asd/100; } 

 0.05 0.56 5.6 56.0 

Everything works except the last 2 numbers. The problem is that there should be 5.60 and 56.00. And we have 5.6 and 56.0

What am I doing wrong?

  • String.format and you will be happy - gil9red

1 answer 1

A bit of theory:

In order to return the data, you need to format it. You can use the .format () method from the String class, which will return the formatted data as a string.

 public PrintStream format(String format, Object... args) 
  • String format is a string that defines a pattern according to which formatting will occur.

  • Object ... args are the arguments referenced by format specifiers in the format string. If there are more arguments than the format specifiers, the additional arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited to the maximum size of the Java array, as determined by the Java ™ Virtual Machine Specification. The behavior on the zero argument depends on the conversion.

Taken from off. Oracle documentation

According to the pattern given by us, we take the argument numbered %1$ and say that we need to output .2f - two decimal places.

Decision:

Change your Convert function as follows:

  public String convert(String str) { double myDouble = Double.valueOf(str) / 100; return String.format("%1$,.2f", myDouble); } 

Hope my answer helped you.

  • Thanks It works. Could you explain what it is and how it works? - Andro
  • @Andro corrected the answer, if there are more questions, I will try to help - Timur Mukhortov