Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!

# How to best convert for example 2.29 -> 2.3

Dominic Steng�rd
Ranch Hand
Posts: 186
Hi all math foks!
I want to find a nice and small algorithm for converting double/float values like 2.29 -> 2.3 or 8.33 -> 8.3 ...
I have a solution but I'm not satisfied with it ... have you got any ideas?
Regards

Marilyn de Queiroz
Sheriff
Posts: 9063
12
How about using the Math.round() method.

Dominic Steng�rd
Ranch Hand
Posts: 186
Because they return an int or long, I need a float or double.
Regards

Dominic Steng�rd
Ranch Hand
Posts: 186
the solution I have figured out is this:
double i = 7;
double j = 4;
double sum = j/i * 100;
int tal = (int) sum;
double decimal = Math.round((sum - tal) * 10);
decimal = decimal/10;
sum = tal + decimal;
but it seems like alot of code for such a small operation ...

Marilyn de Queiroz
Sheriff
Posts: 9063
12
2.29 -> 2.3

double d = Math.round(2.29 * 10)/10.0

??

Dominic Steng�rd
Ranch Hand
Posts: 186
Thanks Marilyn! That is less code than the solution I had ...