1

I have this code:

StringBuilder sbp = new StringBuilder().append(
   String.valueOf((temp / 10F)))
   .append(" \260C / ").append(String.valueOf((temp/10F)*9/5+32))
   .append(" \260F");

and I get this result:

 29.8 C / 85.641 F

I want to format the float numbers to show max 1 digit after decimals, 85.6 instead of 85.641

Mario
  • 13,941
  • 20
  • 54
  • 110
  • I think this is a duplicate http://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0 – bhspencer Jan 23 '15 at 22:52
  • not really, because I needed the format for StringBuilder, but it seems that I still need to make a String.format first and then append to StringBuilder – Mario Jan 23 '15 at 23:00

2 Answers2

4

You could achieve this using String.format instead:

String s = String.format("%.1f C / %.1f F", temp / 10F, (temp/10F)*9/5+32);
Alan
  • 2,962
  • 2
  • 15
  • 18
1

Here's a simple example that you can implement in your StringBuilder:

float num = 85.641f;
num = Math.round(num * 10) / 10f; // pi is now 85.6
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70