• 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:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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: 61697
193
  • 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: 61697
193
  • 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
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!