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

2
  • I think this is a duplicate stackoverflow.com/questions/703396/… Commented Jan 23, 2015 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 Commented Jan 23, 2015 at 23:00

2 Answers 2

4

You could achieve this using String.format instead:

String s = String.format("%.1f C / %.1f F", temp / 10F, (temp/10F)*9/5+32);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks !, now I can append the s to stringbuilder
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

3 Comments

How about this, Mario? What do you think Alan?
All you have to do is cast to a string with String.valueOf(num).
I need to do this with each number, which makes the code redundant, the answer from Alan is much more compact.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.