Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

formatting to 4 decimal places  RSS feed

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
my problem is that to get the data to a jTextField it had to be cast to string i need to format it to 3 or4 decimal places i cant seem to find anything to do it can anyone give me some guidance.

Thanks
 
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Terry,

You'll want to use DecimalFormat to get your number to appear in the desired format. An example format to display to the third (or fourth if relevant) decimal might be:

 
Marshal
Posts: 59700
187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As an alternative for Java5 or Java6 use the static format method of the String class.
. . . String.format("%6.3f", doubleNumber);
 
terry oliver
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks very much worked perfectly saved some of my hair

olly
 
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class formatdemo {

/**
* @param args
*/
public static void main(String[] args)
{

Float myNumber = new Float(4.995);
String myValue = String.format("%1.3f", myNumber);
System.out.println(myValue);
}

}

o/p - 4.995
Can't it roundoff the no.
 
Campbell Ritchie
Marshal
Posts: 59700
187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Dinesh Tahiliani:
Can't it roundoff the no.

If you pass a number with 3 decimal places and print it with 3 decimal places there won't be any rounding. Try with 4.99999995
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!