programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# How to round a double decimal number ?

Dalin Mansour
Greenhorn
Posts: 12
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
• 1

Dalin Mansour
Greenhorn
Posts: 12
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
Don't use decimal format. Use String#format as Knute suggested. It is much easier to use.

Dalin Mansour
Greenhorn
Posts: 12
That's true Ritchie I think it is much easier than decimal format. Thanks a lot.

Campbell Ritchie
Marshal
Posts: 56600
172
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.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?