1

I’m trying to print a number with digits after the decimal point, but i want to show just one digit.

ratio = (double) comparisons / arrayLength;

(while ratio is double and comparisons , arrayLength is int).

i'm doing the calculation in one class and add the result to a string (when later is returned from a method), and doing the printing in a test class.

i need to change ratio and not allowed to use printf in the test class.

thanks for your help

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
aye
  • 17
  • 1
  • 6
  • 1
    Welcome to Stack Overflow. Please search before asking and find several good answers faster than anyone can type a new one. – Ole V.V. Apr 11 '20 at 19:02

2 Answers2

1

Since you're already keeping the result in a string, you can do this-

 String result = String.format("%.1f",ratio);

If you want to add the answer to an existing string then you can do this-

result = String.format(result+"%.1f",ratio);

An example would be like this-

 String s = String.format("%.1f",2.3535);

Output- 2.4

ChasedByDeath
  • 183
  • 3
  • 15
0

You could explicitly format the number with a DecimalFormat:

DecimalFormat df = new DecimalFormat("###.#");
String formatted = df.format(ratio);
System.out.printly("ratio is " + ratio);
Mureinik
  • 297,002
  • 52
  • 306
  • 350