This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How to best convert for example 2.29 -> 2.3 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to best convert for example 2.29 -> 2.3 " Watch "How to best convert for example 2.29 -> 2.3 " New topic
Author

How to best convert for example 2.29 -> 2.3

Dominic Steng�rd
Ranch Hand

Joined: Feb 05, 2001
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?
Thanks in advance!
Regards


Dominic Steng�rd<br />Sun Certified Java 2 Programmer
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
How about using the Math.round() method.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Dominic Steng�rd
Ranch Hand

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

Joined: Feb 05, 2001
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

Joined: Jul 22, 2000
Posts: 9044
    
  10
2.29 -> 2.3

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

??
Dominic Steng�rd
Ranch Hand

Joined: Feb 05, 2001
Posts: 186
Thanks Marilyn! That is less code than the solution I had ...
Steve Deadsea
Ranch Hand

Joined: Dec 03, 2001
Posts: 125
I wrote a Significant Figures class that can do rounding like this. I found that when a number is to be displayed, its easiest to manipulate it in String format. You can find the class and source here:
http://ostermiller.org/utils/SignificantFigures.html
 
 
subject: How to best convert for example 2.29 -> 2.3