• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to round a double decimal number ?  RSS feed

 
Dalin Mansour
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please help. I want to round a double decimal number for temperature degrees . Any suggestions please>?
This is my code:
double f = Double.parseDouble(result.getText());

double c = ((f - 32) * 5) / 9;
//int b = (int)c;
cTemp = Double.toString(c);
result.setText(String.valueOf(b));
 
Knute Snortum
Sheriff
Posts: 4288
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try String.format().
 
Dalin Mansour
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I changed my code. here is the new one:
public void actionPerformed(ActionEvent event)
{
double f = Double.parseDouble(result.getText());
//convert from fehrinhite to celisus
double c = ((f - 32) * 5) / 9;
//turn double c to integer
DecimalFormat df = new DecimalFormat("#");
cTemp = Double.toString(c);
result.setText(df.format(c));
}
}
It works perfect. Thank you Knute...you helped me a lot.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use decimal format. Use String#format as Knute suggested. It is much easier to use.
 
Dalin Mansour
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's true Ritchie I think it is much easier than decimal format. Thanks a lot.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dalin Mansour wrote: . . .
//turn double c to integer
DecimalFormat df = new DecimalFormat("#");
. . .
Beware. Look up the documentation for decimal format. The NumberFormat#format method will round according to the RoundingMode set on that instance. Conversion to an integer with a cast always uses round‑towards‑zero. Try it with 48℉ which should equal 8.88888…℃. Casting to an int gives you 8 but rounding usually gives you 9.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!