• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to best convert for example 2.29 -> 2.3

 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How about using the Math.round() method.
 
Dominic Steng�rd
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because they return an int or long, I need a float or double.
Regards
 
Dominic Steng�rd
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
2.29 -> 2.3

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

??
 
Dominic Steng�rd
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Marilyn! That is less code than the solution I had ...
 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
reply
    Bookmark Topic Watch Topic
  • New Topic