Mario
Mario

Reputation: 14790

How to format a float number in java String.ValueOf

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

Upvotes: 1

Views: 4567

Answers (2)

Malik Brahimi
Malik Brahimi

Reputation: 16711

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

Upvotes: 1

Alan
Alan

Reputation: 3002

You could achieve this using String.format instead:

String s = String.format("%.1f C / %.1f F", temp / 10F, (temp/10F)*9/5+32);

Upvotes: 4

Related Questions